Sunday, October 25, 2009

Adding and Removing Items in a List










Adding and Removing Items in a List






list1.append("Four")
list1.insert(2, "Two 1/2")
list1.extend(list2)
print list1.pop(2)
list1.remove("Five")
list1.remove("Six")




Items can be added to an existing list in several different ways, depending on what items you want to add to the list and where you want to add them.


The simplest way to add a single item to a list is to use the append(item) method. append takes a single itemwhich can be any Python object, including other listsas the only parameter and adds it to the end of the list. If you specify a list as the parameter to the append method, that list is added as a single item in the current list.


Use the extend(list) method to add several items stored in another list all together at the same time. extend will accept only a list as an argument. Unlike the append method, each item in the new list will be appended as its own individual item to the old list.


The extend and append methods will add items only to the end of the list. Use the insert(index, item) method to insert an item in the middle of the list. The insert method accepts a single object as the second parameter and inserts it into the list at the index specified by the first argument.


Items can be removed from a list in one of two ways. The first way is to use the pop(index) method to remove the item by its index. The pop method removes the object from the list and then returns it.


The second way to remove an item from a list is to use the remove(item) method. The remove method will search the list and remove the first occurrence of the item.


Note



You can also add one or more lists to an existing list by using the += operator.




list1 = ["One", "Two", "Three"]
list2 = ["Five", "Six"]

print list1

#Append item
list1.append("Four")
print list1

#Insert item at index
list1.insert(2, "Two 1/2")
print list1

#Extend with list
list1.extend(list2)
print list1

#Pop item by index
print list1.pop(2)
print list1

#Remove item
list1.remove("Five")
list1.remove("Six")
print list1

#Operators
list1 += list2
print list1


add_list.py


['One', 'Two', 'Three']
['One', 'Two', 'Three', 'Four']
['One', 'Two', 'Two 1/2', 'Three', 'Four']
['One', 'Two', 'Two 1/2', 'Three', 'Four',
'Five', 'Six']
Two 1/2
['One', 'Two', 'Three', 'Four', 'Five', 'Six']
['One', 'Two', 'Three', 'Four']
['One', 'Two', 'Three', 'Four', 'Five', 'Six']


Output from add_list.py code












No comments: