|
Academic Work Personal
|
Python /
Basic Datatypes: Lists
This is the most important datatype in Python, this is what you'll use the most. It's a dynamic array actually.
list = [] # empty list
li = ['vader', 'luke', 'boba', 'jabba', 'yoda']
print len(li) # 5
print li[-1] # yoda
print li[1:3] # luke, boba (3-1=2, i.e. this slice has 2 elems). The end index is EXCLUSIVE.
print li[0:-1] # vader, luke, boba, jabba (everything, except the last elem)
# slicing shorthand
print li[:3] # vader, luke, boba
print li[3:] # jabba, yoda
print li[:] # a complete copy of li (this is a different list!)
li.remove('yoda') # vader, luke, boba, jabba
li.append('jabba') # vader, luke, boba, jabba, jabba
li.remove('jabba') # removes the FIRST occurrence only
print li # ['vader', 'luke', 'boba', 'jabba']
li.insert(1, 'solo') # insert 'solo' BEFORE the elem at position 1, i.e. before 'luke'
print li # ['vader', 'solo', 'luke', 'boba', 'jabba']
li.extend(['a', 'b', 'c']) # extend has 1 argument, which is ALWAYS a list
print li # ['vader', 'solo', 'luke', 'boba', 'jabba', 'a', 'b', 'c']
li.append(['d', 'e']) # insert one element, a list, i.e. the last elem will be a nested list
print li # ['vader', 'solo', 'luke', 'boba', 'jabba', 'a', 'b', 'c', ['d', 'e']]
print li.index('boba') # 3 (finds the FIRST occurrence)
print 'vader' in li # True
print 'yoda' in li # False
lastElem = li.pop() # remove the last elem and return it
print lastElem # ['d', 'e']
print li # ['vader', 'solo', 'luke', 'boba', 'jabba', 'a', 'b', 'c']
li = ['a', 'b']
li += ['c', 'd'] # like extend()
print li # ['a', 'b', 'c', 'd']
li = li + ['x', 'y'] # SLOW! Returns a NEW list while extend() alters an existing list IN PLACE.
li = [3, 5] * 3
print li # [3, 5, 3, 5, 3, 5]
Some List Functions
|
![]() anime | bash | blogs | bsd | c/c++ | c64 | calc | comics | convert | cube | del.icio.us | digg | east | eBooks | egeszseg | elite | firefox | flash | fun | games | gimp | google | groovy | hardware | hit&run | howto | java | javascript | knife | lang | latex | liferay | linux | lovecraft | magyar | maths | movies | music | p2p | perl | pdf | photoshop | php | pmwiki | prog | python | radio | recept | rts | scala | scene | sci-fi | scripting | security | shell | space | súlyos | telephone | torrente | translate | ubuntu | vim | wallpapers | webutils | wikis | windows Blogs and Dev. * Ubuntu Incident Places Debrecen | France | Hungary | Montreal | Nancy Notes Hobby Projects * Jabba's Codes Quick Links [ edit ] |