Tuesday, July 7, 2009

The Python list and methods of the python list

# basic list usage and list methods 
 
# a list is created with the "[]" square brackets 
l = []
 
# add a single item into a list 
l.append("apple")
print l
#output: 
# apple 
 
# remove the last item appended 
l.pop()
#output: 
# apple 
 
print len(l)
#output: 
# 0 
 
# create and then iterate through a list 
l.append("apple")
l.append("pear")
l.append("peach")
l.append("apricot")
l.append("banana")
print l
#output: 
# ['apple', 'pear', 'peach', 'apricot', 'banana'] 
 
for fruit in l:
    print fruit
 
#output 
#    apple 
#    pear 
#    peach 
#    apricot 
#    banana 
 
# find the index of items in a list 
l.index("apricot")
#output: 3 
l.index("apple")
#output: 0 
 
# remove specific items from a list 
print l
#output: 
# ['apple', 'pear', 'peach', 'apricot', 'banana'] 
 
l.remove("peach")
print l
#output: 
# ['apple', 'pear', 'apricot', 'banana'] 
 
 
# More on lists:  http://docs.python.org/tutorial/datastructures.html  
 

No comments:

Post a Comment