Lists, Tuples and Dictionaries

© QuantSprout

The next basic data type is the Python list. A list is an ordered collection of elements, and these elements can be of arbitrary type. Lists are mutable, meaning they can be changed in-place. In python lists are indicated by square brackets [ and ]. Items in a list are indexed starting with 0.

List Basics

x = [1, 'b', True]
x[1] = 'a'
print x
[1, 'a', True]

You can even have lists of lists:

a = [[1,2,3], 4, 5]

Use multiple indexes for lists within lists

print a[0]
print a[0][1]

Index from the end of the list

print a[-1]

Append an item to a list

a.append('one more item')

Reference multiple items in a list

print a[2:4]
[5, 'one more item']

Open ended indexes go to the ends of lists

print a[:3]
[[1, 2, 3], 4, 5]

Python tuples

Tuples are similar to lists, except that they are immutable, meaning that they cannot be changed in place. Tuples are indicated by parenthesis ( and ).

x = (1, 'a', 2.5)
(1, 'a', 2.5)
x[0] = 'b'
TypeError                                 Traceback (most recent call last)
<ipython-input-30-1d938b100406> in <module>()
----> 1 x[0] = 'b'

TypeError: 'tuple' object does not support item assignment

Python dictionaries

Dictionaries are unordered collections of key-value pairs. Dictionaries can use various types for keys (e.g. strings, ints) so long as the key is immutable. Values are looked up by key. In python dictionaries are indicated by curly braces { }

Create a dictionary

info = {'name': 'Bob', 'age': 54, 'kids': ['Henry', 'Phil']}

Lookup value with key


Change a value for a key

info['age'] = 55
print info['kids']
print info['kids'][0]
['Henry', 'Phil']

Get all keys in dictionary

['age', 'kids', 'name']

Get all values in dictionary

[55, ['Henry', 'Phil'], 'Bob']

Check if key exists