Question

Deletion of List Elements The del statement removes an element or slice from a list by position....

Deletion of List Elements

  • The del statement removes an element or slice from a list by position.
  • The list method list.remove(item) removes an element from a list by it value (deletes the first occurance of item)
  • For example:
        
    a = ['one', 'two', 'three']
    del a[1]
    for s in a:
        print(s)
    
    b = ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b']
    del b[1:5]
    print(b)
    
    b.remove('a')
    print(b)
        
    # Output:
    '''
    one
    three
    ['a', 'f', 'a', 'b']
    ['f', 'a', 'b']
    '''
    
  • Your textbook documents other List Methods in section 10.14. You can also find the more complete documentation of List methods here in the Python documenation.

Reference Variables

  • A reference variable stores the memory address of an object. It's similar to the C++ concept of a pointer. So when we access a reference variable, it indicates where to find the actual data we want, and we get it from there automatically. This allows two different reference variables to refer to the same actual object (the same memory address).
  • In Python, all variables are objects, so they all use reference variables. But in many other languages, such as C++ and Java, simple data (such as ints and floats) are stored directly, without reference variables.
  • To avoid confusion and mistakes, the common data types are all immutable in Python, so that we don't have to worry about modifying shared data. This includes strings, ints, floats, and bools.
  • Since lists are mutable, we have to be more careful about references to shared data, and knowing whether or not we are changing it.
  • None - keyword indicating an empty reference. This is similar to null in Java. A variable whose value is None is one that doesn't refer to an object.
  • For example, if you assign a variable to store the return value of a function that doesn't have a return statement, the variable will store None.
  • The is operator returns True if two reference variables refer to the same object (the same memory location). Otherwise it returns False.
  • The == operator compares the contents of its arguments (list elements), to see if they have the same value.
  • To copy a list, so that you have two separate objects storing the same data as each other, you can use a slice like this:
    list1 = [1, 2, 3, 4]
    list2 = list1[:]
    print(list1 is list2)  # False
    print(list1 == list2)  # True
       
  • The CodeLens example on this page from the book demonstrates "is" and "==" with reference variables well.

Lists and Functions

  • An entire list can be passed as an argument to a function.
  • The variable you use to refer to the list is really just a reference to the array's contents. Since a list is mutable, its contents may be changed by the function.
  • Example: ArrayParam.py.txt - Demonstrates how array parameters work
  • In-class exercise: write the method inputList to make this program work as shown.
# CS 110A - Starting poing for in-class exercise on List References and Functions


def main():
    a = []
    inputList(a)
    print("Here are the names you entered (excluding Craig):")
    for item in a:
        print(item)


# Insert your code here 
# Write the inputList function so that the program produces the output below.


main()

# Sample output:
'''
Please input one name on each line, hitting Enter on a blank line when finished:
 Craig
 Indika
 Deepa
 Man
 
Here are the names you entered (excluding Craig):
Indika
Deepa
Man
'''
'''
Please input one name on each line, hitting Enter on a blank line when finished:
 Erez
 Dan
 Craig
 Anita
 Henry
 
Here are the names you entered (excluding Craig):
Erez
Dan
Anita
Henry
'''
0 0
Add a comment Improve this question Transcribed image text
Answer #1

def main():
a = [] # creating empty list
inputList(a) # calling method below
print("Here are the names you entered (excluding Craig):")   
for item in a:
print(item) # printing elements of modified list a
# Insert your code here
# inputlist function that takes empty list, asks user to enter names, store them in list and removes Craig from it
def inputList(a):
print('Please input one name on each line, hitting Enter on a blank line when finished:') # printing instruction
name = raw_input(); # taking input name
while ( name !=''): # looping until user presses Enter (name = '' )
a.append(name) # this functions adds new element (name) to list a
name = raw_input(); # taking input again
a.remove('Craig') # removing first occurance of name 'Craig'
main()

1 def main(): 2 3 inputlist (a) 4 print( Here are the names you entered (excluding Craig):) 5 for item in a: creating empty

Sample outputs:

Please input one name on each line, hitting Enter on a blank line when finished: Craig Indika Deepa Man Here are the names yo

Please input one name on each 1line, hitting Enter on a blank line when finished: Erez Dan Cra1g Anita Henry Here are the nam

Add a comment
Know the answer?
Add Answer to:
Deletion of List Elements The del statement removes an element or slice from a list by position....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a Python program (remove_first_char.py) that removes the first character from each item in a list...

    Write a Python program (remove_first_char.py) that removes the first character from each item in a list of words. Sometimes, we come across an issue in which we require to delete the first character from each string, that we might have added by mistake and we need to extend this to the whole list. Having shorthands (like this program) to perform this particular job is always a plus. Your program should contain two functions: (1) remove_first(list): This function takes in a...

  • Something is preventing this python code from running properly. Can you please go through it and...

    Something is preventing this python code from running properly. Can you please go through it and improve it so it can work. The specifications are below the code. Thanks list1=[] list2=[] def add_player(): d={} name=input("Enter name of the player:") d["name"]=name position=input ("Enter a position:") if position in Pos: d["position"]=position at_bats=int(input("Enter AB:")) d["at_bats"] = at_bats hits= int(input("Enter H:")) d["hits"] = hits d["AVG"]= hits/at_bats list1.append(d) def display(): if len(list1)==0: print("{:15} {:8} {:8} {:8} {:8}".format("Player", "Pos", "AB", "H", "AVG")) print("ORIGINAL TEAM") for x...

  • Need help solving this qestion related to object and item classes involving arrays in PYTHON. Classes...

    Need help solving this qestion related to object and item classes involving arrays in PYTHON. Classes and Object - Inventory Item as Object                    In this assignment the idea is to use an Item class to capture what you need for recording and displaying the details of an order from an online store like Amazon. This is a Class and Object assignment. For the assignment you must define and implement the Item class so that the code shown immediately below can...

  • C++ LAB 19 Construct functionality to create a simple ToDolist. Conceptually the ToDo list uses a...

    C++ LAB 19 Construct functionality to create a simple ToDolist. Conceptually the ToDo list uses a structure called MyToDo to hold information about each todo item. The members of the MyToDo struct are description, due date, and priority. Each of these items will be stored in an array called ToDoList. The definition for the MyToDo struct should be placed in the header file called ToDo.h Visually think of the ToDoList like this: There are two ways to add items to...

  • This class implements a doubly linked list in which the nodes are of the class DLNode....

    This class implements a doubly linked list in which the nodes are of the class DLNode. This class must implement the interface DLListADT.java that specifies the public methods in this class. The header for this class will then be public class DLList implements DLListADT This class will have three private instance variables: • private DLNode front. This is a reference to the first node of the doubly linked list. • private DLNode rear. This is a reference to the last...

  • Download BankAccount.java and BankAccountTester.java starting files and drag and drop them into your eclipse project. The...

    Download BankAccount.java and BankAccountTester.java starting files and drag and drop them into your eclipse project. The BankAccount class declaration in file BankAccount.java is the blueprint of a BankAccount object. Check out the design of a BankAccount class. 1. In BankAccount.java class, all of the method stubs ( methods with a header but empty bodies ) are present to help you get started. Your task is to complete the method bodies. All comments in red in the diagram above indicates what...

  • I NEED HELP WITH THIS HOMEWORK!!!! What is a characteristic of a bag data type? Elements...

    I NEED HELP WITH THIS HOMEWORK!!!! What is a characteristic of a bag data type? Elements are added and removed in any order Elements are removed in the same order they were added Distinct elements are added in any order but are removed beginning with the last one added Distinct elements are removed in the reverse order they were added Which scenario illustrates a data stack structure Standing in a line to be serviced Filing documents in alphabetical order Offering...

  • Write three object-oriented classes to simulate your own kind of team in which a senior member...

    Write three object-oriented classes to simulate your own kind of team in which a senior member type can give orders to a junior member type object, but both senior and junior members are team members. So, there is a general team member type, but also two specific types that inherit from that general type: one senior and one junior. Write a Python object-oriented class definition that is a generic member of your team. For this writeup we call it X....

  • c++ only Program 2: Linked List Class For this problem, let us take the linked list...

    c++ only Program 2: Linked List Class For this problem, let us take the linked list we wrote in a functional manner in a previous assignment and convert it into a Linked List class. For extra practice with pointers we’ll expand its functionality and make it a doubly linked list with the ability to traverse in both directions.    Since the list is doubly linked, each node will have the following structure: struct Node { int number; Node * nextNode;...

  • D Question 12 1.5 pts Check the true statements about NumPy arrays: O A single instantiated NumPy array can store multi...

    D Question 12 1.5 pts Check the true statements about NumPy arrays: O A single instantiated NumPy array can store multiple types (e.g., ints and strings) in its individual element positions. A NumPy array object can be instantiated using multiple types (e.g., ints and strings) in the list passed to its constructor O Memory freeing will require a double-nested loop. The number of bits used to store a particular NumPy array object is fixed. O The numpy.append(my.array, new_list) operation mutates...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT