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

In [18]:
x = [1, 'b', True]
In [19]:
x[2]
Out[19]:
True
In [20]:
x[1] = 'a'
print x
[1, 'a', True]

You can even have lists of lists:

In [21]:
a = [[1,2,3], 4, 5]

Use multiple indexes for lists within lists

In [22]:
print a[0]
print a[0][1]
Out[22]:
2

Index from the end of the list

In [23]:
print a[-1]
Out[23]:
5

Append an item to a list

In [24]:
a.append('one more item')

Reference multiple items in a list

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

Open ended indexes go to the ends of lists

In [26]:
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 ).

In [27]:
x = (1, 'a', 2.5)
In [28]:
x
Out[28]:
(1, 'a', 2.5)
In [29]:
x[0]
Out[29]:
1
In [30]:
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

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

Lookup value with key

In [9]:
info['name']
Out[9]:
'Bob'

Change a value for a key

In [34]:
info['age'] = 55
In [35]:
print info['kids']
print info['kids'][0]
['Henry', 'Phil']
Henry

Get all keys in dictionary

In [36]:
info.keys()
Out[36]:
['age', 'kids', 'name']

Get all values in dictionary

In [37]:
info.values()
Out[37]:
[55, ['Henry', 'Phil'], 'Bob']

Check if key exists

In [38]:
info.has_key('age')
Out[38]:
True