'Scalar' data types

In [1]:
an_int = 3
a_string = 'foobat'
a_double = 3.9
a_bool = True

'Compound' data types combine multiple pieces of data into a bigger whole.

In [2]:
a_list = [3, 4, 72, 'wombat']
a_dict = {
    'name': 'wombat',
    'location': 'australia',
    'lethality': 'medium'
}

In C++:

class animal {
public:
    const string& name();
private:
    string name;
    string location;
    string lethality;
}
In [10]:
animals = [
    {
        'name': 'wombat',
        'location': 'australia',
        'lethality': 'medium',
        'possible_colors': ['brown', 'grey']
    },
    {
        'name': 'rabbit',
        'location': 'england',
        'lethality': 'low',
        'possible_colors': ['white', 'black', 'grey', 'brown', 'purple']
    },
    {
        'name': 'white rabbit',
        'location': 'england',
        'lethality': 'high',
        'nemesis': 'King Arthur',
        'possible_colors': ['white']
    }
]

It's useful to structure our lists so that everything in a list is the same kind of thing with the same basic structure. Otherwise, our loops have to do complex things to figure out what on earth they're looking at.

Where do things live?

In [12]:
for animal in animals:
    if animal['lethality'] == 'low':
        leth_msg = 'will probably not'
    elif animal['lethality'] == 'medium':
        leth_msg = 'might'
    elif animal['lethality'] == 'high':
        leth_msg = 'will probably'
    else:
         leth_msg = 'may or may not, it\'s unclear,'
    print('The {} lives in {}. It {} try to kill you.'.format(animal['name'], animal['location'], leth_msg))
    print('It can appear in the following colors:')
    for color in animal['possible_colors']:
        print('- ' + color)
    if 'nemesis' in animal:
        print('Its nemesis is {}'.format(animal['nemesis']))
The wombat lives in australia. It might try to kill you.
It can appear in the following colors:
- brown
- grey
The rabbit lives in england. It will probably not try to kill you.
It can appear in the following colors:
- white
- black
- grey
- brown
- purple
The white rabbit lives in england. It will probably try to kill you.
It can appear in the following colors:
- white
Its nemesis is King Arthur
In [13]:
# The 'key' parameter provides an expression to extract an attribute
# Sort will then sort by that, instead of trying to sort dictionaries
for animal in sorted(animals, key=lambda a: a['name']):
    print(animal['name'])
rabbit
white rabbit
wombat
In [14]:
# Let's sort the other way
for animal in sorted(animals, key=lambda a: a['name'], reverse=True):
    print(animal['name'])
wombat
white rabbit
rabbit
In [ ]: