Several instances demonstrate the charm of the data structure list in python!
List variable Declaration
the_count = [1, 2, 3, 4, 5]fruits = ['apples', 'oranges', 'pears', 'apricots']change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
Access list elements
Array = [, 4] # In fact, the sequential identifier here is (, 6) (-7,-6,-5,-4, -3,-2,-1) # There are negative subscripts. array [0:] # list [1, 2, 5, 3, 6, 8 after index = 0, 4] array [1:] # list [,] array [:-1] # list, 5, 3, 6, 8] array [3:-3] # list the values between index = 3 and index =-3. Note that index =-3 is not included, that is, left closed and right open [3]
List Application loops and list
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']for i in change: print "I got %r" % i
Enumerate
for i,j in enumerate([[1,2],['o',2],[9,3]]):k1,k2=jprint i,k1,k2
Output
0 1 21 o 22 9 3
Append/extend/pop/delappend () add elements to the end of the list
elements=[1,2,3,4,5]elements.append(6)
Extend () concatenates two lists
list1=[1,2,3,4,5]list2=[6,7]elements.extend(list2)print elements
Pop (int I =-1) deletes the element specified in the list and returns the number at the position. default: deletes the last element.
elements=[1,2,3,4,5]print elements.pop()#default:delete index==-1,i.e. the last elementprint elementselements=[1,2,3,4,5]elements.pop(-2)#delete index==-2,i.e. 4print elementselements.pop(1)print elements
Del
elements=[1,2,3,4,5]del elements[0]#default:delete index==0,i.e. 1print elementselements=[1,2,3,4,5]del elements[2:4]#delete index==2 and index==3,i.e.3 and 4print elementselements=[1,2,3,4,5]del elements#delete allelements
Do things to list
ten_things = "Apples Oranges Crows Telephone Light Sugar"print "Wait there's not 10 things in that list, let's fix that."stuff = ten_things.split(' ')more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]while len(stuff) != 10: next_one = more_stuff.pop() print "Adding: ", next_one stuff.append(next_one) print "There's %d items now." % len(stuff)print "There we go: ", stuffprint "Let's do some things with stuff."print stuff[1]print stuff[-1] # whoa! fancyprint stuff.pop()print ' '.join(stuff) # what? cool!print '#'.join(stuff[3:5]) # super stellar! outputs:stuff[3]#stuff[4]
''. Join (things)Reads as, "Join things with ''between them." Meanwhile, Join ('', things)Means, "Call join with'' and things. Returns a string.
Output
Wait there's not 10 things in that list, let's fix that.Adding: BoyThere's 7 items now.Adding: GirlThere's 8 items now.Adding: BananaThere's 9 items now.Adding: CornThere's 10 items now.There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']Let's do some things with stuff.OrangesCornBanana['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Corn']Apples Oranges Crows Telephone Light Sugar Boy Girl CornTelephone#Light#Sugar