Python Cheat Sheet: Lists
Lists are ordered, linear collections that offer constant-time element lookup by index. They can grow or shrink, be searched, and be sorted (including with a custom comparison function). They also aren’t limited to one data type, so a single list can hold a mix of values. Python lists are zero-indexed.
Note: Unless stated otherwise, all examples use Python 2 syntax.
A = [0] * 10
A = [2**i for i in xrange(0, 10)]
Note 1: xrange in the example above produces the values 0 through 9, inclusive.
Note 2: This syntax is called a list comprehension.
A = [0, 'a', {'b': 'c'}]
for e in A:
print e
A = [0, 'a', {'b': 'c'}]
for i in xrange(len(A)):
print i, A[i]
A = [0, 1, 2, 3]
A += [4]
Note: The append method can be used for the same purpose.
A = [0, 1, 2, 3]
A.insert(0, -1) # position, value
Note: The insert call above places the new element at the front of the list.
A = [0, 1, 2, 3]
A.index(2)
Note: index performs a linear search for the given value. If the value isn’t in the list, a ValueError is raised.
A = [0, 1, 2, 3]
A.remove(2) # by value
del A[1] # by index
A = []
A.append(1)
A.append(2) # always add to the end
stacktop = A.pop() # returns 2, the most recently added element
Note: pop raises an IndexError if the list is empty.
A = []
A.insert(0, 1)
A.insert(0, 2) # always insert at the front of the list
elem = A.pop() # returns 1, the earliest element added
Note: For an optimized implementation of both stacks and queues, take a look at collections.deque.
That’s all for today. Have fun!