Skip to main content

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.

Creating a pre-filled list of 10 numbers (all zeros):

A = [0] * 10

Creating a pre-filled list of 10 numbers (powers of 2):

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.

Looping over every element (read-only):

A = [0, 'a', {'b': 'c'}]
for e in A:
    print e

Looping over every element (read/write):

A = [0, 'a', {'b': 'c'}]
for i in xrange(len(A)):
    print i, A[i]

Appending elements to the end of a list:

A = [0, 1, 2, 3]
A += [4]

Note: The append method can be used for the same purpose.

Inserting elements:

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.

Finding elements in a 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.

Removing elements from a list:

A = [0, 1, 2, 3]
A.remove(2)  # by value
del A[1]     # by index

Using a Python list as a stack:

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.

Using a Python list as a queue:

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!