Python - Data Structure


List (Array):

a = ['spam', 'eggs', 100, 1234]
a[0:2] = [1, 12]   // replace the first 2 items
a[0:2] = []           // remove the first 2 items
a[1:1] = ['bletch', 'xyzzy']  // insert two items
a[:0] = a              // insert a copy of itself at the beginning
a[:] = []                // clear the list
a[:]                       // an anonymous copy of a

List indices start at 0, and lists can be sliced, concatenated and so on. The built-in function len() also applies to lists:


It is possible to nest lists (create lists containing other lists).

list.append(x)  // Add an item to the end of the list
list.extend(L)   // Extend the list by appending all the items in the given list
list.insert(i, x)  // Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list
list.remove(x)  // Remove the first item from the list whose value is x. It is an error if there is no such item.
list.pop([i])      // Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. 
list.index(x)     // Return the index in the list of the first item whose value is x. It is an error if there is no such item.
list.count(x)     // Return the number of times x appears in the list.
list.sort()         // Sort the items of the list, in place.
list.reverse()   // Reverse the elements of the list, in place.
del a[0]           // remove the first item from the list (does not return the item, if you need the item use list.pop(0)
del a                // delete entire variable.  Referencing the name a hereafter is an error (at least until another value is assigned to it).

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function:

for i, v in enumerate(['tic', 'tac', 'toe']):
    print i, v

To loop over two or more sequences at the same time, the entries can be paired with the zip() function:

questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
    print 'What is your {0}?  It is {1}.'.format(q, a)

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function:

for i in reversed(xrange(1,10,2)):
    print i


A tuple consists of values separated by commas:

t = 12345, 54321, 'hello!'

Output of tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly. They may be input with or without surrounding parentheses.

Tuples have many uses. For example: (x, y) coordinate pairs, employee records from a database, etc. Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple (you can simulate much of the same effect with slicing and concatenation, though). It is also possible to create tuples which contain mutable objects, such as lists. To construct a tuple of one item (note the trailing comma is required):

singleton = 'hello',

The statement

t = 12345, 54321, 'hello!'

is an example of tuple packing: the values 12345, 54321 and 'hello!' are packed together in a tuple. The reverse operation is also possible:
x, y, z = t

This is called sequence unpacking. Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence. Multiple assignment is really just a combination of tuple packing and sequence unpacking!


A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
fruit = set(basket)               # create a set without duplicates
'orange' in fruit                 # fast membership testing

# Demonstrate set operations on unique letters from two words
a = set('abracadabra')
b = set('alacazam')
a - b                              # letters in a but not in b
a | b                              # letters in either a or b
a & b                              # letters in both a and b
a ^ b                              # letters in a or b but not both


Dictionaries are sometimes found in other languages as “associative arrays”. Dictionaries are indexed by keys, which can be any immutable type. Strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples. If a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified.

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique. A pair of braces creates an empty dictionary: {}.

It is also possible to delete a key:value pair with del. It is an error to extract a value using a non-existent key.

The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order. To check whether a single key is in the dictionary, use the 'in' keyword.

tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127

The dict() constructor builds dictionaries directly from lists of key-value pairs stored as tuples. When the pairs form a pattern, list comprehensions can compactly specify the key-value list.

dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
dict([(x, x**2) for x in (2, 4, 6)])     # use a list comprehension
dict(sape=4139, guido=4127, jack=4098)  # keyword assignment form

When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the iteritems() method:

knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.iteritems():
    print k, v
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License