A list of pairs

In instead of having two lists to contain the model name in one of them and the corresponding characteristic in the other we can have one only list containing pairs (or triples or whatever) of values, or tuples in python parlance.

Let's associate models with their corresponding accelerations from 0 to 60 mph:

>>> model_list = [('BMW Z4', 8.7), ('Audi TT', 8.6), ('Mercedez CLK350', 8.8)]
>>> model_list
[('BMW Z4', 8.69999999993), ('Audi TT', 8.59999999996), ('Mercedez CLK350', 8.80000000007)]
>>>

Those pairs inside parenthesis are the so called tuples.

The first element in the list, a tuple in this case, is model_list[0] exactly as if it was a single value:

>>> model_list[0]
('BMW Z4', 8.6999999999999993)
>>>

The interesting part: Guess how we call the first element of the first tuple? We already now the first tuple is model_list[0]. The first element of the first tuple is model_list[0][0] :

>>> model_list[0][0]
'BMW Z4'
>>> model_list[0][1]
8.6999999999999993

Now if we want to show it all:

>>> print model_list[0][0], "acceleration is", model_list[0][1], "seconds"
BMW Z4 acceleration is 8.7 seconds
>>> print model_list[1][0], "acceleration is", model_list[1][1], "seconds"
Audi TT acceleration is 8.6 seconds
>>> print model_list[2][0], "acceleration is", model_list[2][1], "seconds"
Mercedez CLK350 acceleration is 8.8 seconds
>>>

Proposed exercise

Change this list to also include mileage and price of each model.

computer programming degree learning course tutorial