Is a tuple a list of lists?

The Python tuple is an alternative to the list structure. The example below shows how to construct a tuple.

contact = ('Joe Gregg','832-6736')

Unlike lists, which can have items appended or removed from them via the use of list methods, the tuple is an immutable structure. The tuple in the example above has two items in it: this size is fixed and can never be changed.

You can access the elements in a tuple using the same index notation you would use with a list.

phone = contact[1]

You can also update the entries in a tuple by assigning new values to them.

contact[1] = '555-1212'

An example

Tuples are especially useful in situations where data items belong together and would not make sense by themselves.

Here is an example. The list below shows currency codes for a number of currencies and the exchange rate from US dollars to that currency. The numbers in each case show how many units of the currency one US dollar would buy.

exchange = [('EUR' , 0.869335) , ('JPY' , 113.0005) ,\ ('GBP' , 0.760425) , ('AUD' , 1.40553) , ('CAD' , 1.29406) ,\ ('CHF' , 0.99148) , ('CNY' , 6.9228) , ('SEK' , 9.09429) ,\ ('NZD' , 1.54148) , ('MXN' , 18.99626) , ('SGD' , 1.3809)]

Because the list spans multiple lines, I have used the Python continuation character, \, at the end of each line.

Suppose we wanted to write a program that prompts the user to enter a code for a foreign currency and an amount of that currency that the user wants to purchase. The program will compute and print how many US dollars it would take to purchase that many units of the currency. Here some code that will do this.

exchange = [('EUR' , 0.869335) , ('JPY' , 113.0005) ,\ ('GBP' , 0.760425) , ('AUD' , 1.40553) , ('CAD' , 1.29406) ,\ ('CHF' , 0.99148) , ('CNY' , 6.9228) , ('SEK' , 9.09429) ,\ ('NZD' , 1.54148) , ('MXN' , 18.99626) , ('SGD' , 1.3809)] code = input('Enter a currency code: ') amount = float(input('How many units do you want to buy? ') cost = 0 for pair in exchange: if pair[0] == code: cost = amount/pair[1] if cost != 0: print('Your cost is $'+str(cost)) else: print('You did not enter a valid code.')

An alternative to using the index notation for tuples in a for loop is to use a form of the for loop that assigns each member of a tuple to a different loop variable:

for c,r in exchange: if c == code: cost = amount/r

Zip lists

Sometimes you will want to combine data from two separate lists into a single list. A common situation where you might want to do this is printing a table.

In an earlier lecture I showed some code to print a list of data points in a table. Here is the original code.

x = [1935,1940,1945,1950,1955,1960,1965,1970,1975,1980] y = [32.1,30.5,24.4,23,19.1,15.6,12.4,9.7,8.9,7.2] print(' Year Population') for i in range(0,len(x)): print('{:5d} {:>4.1f}'.format(x[i],y[i]))

This code iterates over a list of index values and uses those index values to access elements of both lists.

An alternative approach is to construct a zip list from the original pair of lists and just iterate over that. A zip list formed from a pair of lists is a single lists of tuples, with each pair of data items from the original lists becoming one tuple in the zip list. Here is the table printing example rewritten to use a zip list:

x = [1935,1940,1945,1950,1955,1960,1965,1970,1975,1980] y = [32.1,30.5,24.4,23,19.1,15.6,12.4,9.7,8.9,7.2] data = list(zip(x,y)) print(' Year Population') for year,pop in data: print('{:5d} {:>4.1f}'.format(year,pop))

List comprehensions

A Python list comprehension is a method for constructing a list from a list, a range, or other iterable structure. List comprehensions are frequently used to extract data from other lists or to generate new data from an existing data list.

Here is an example. Suppose we wanted to make a list of just the currency codes from the example above. We could do this by using a combination of a loop and the list append() method.

allCodes = [] for c,r in exchange: allCodes.append(c)

A list comprehension provides a more compact way to accomplish the same thing.

allCodes = [c for r,c in exchange]

Another common application of list comprehensions is making lists from ranges. For example, if we wanted to make a list of powers of 2 we could use the following code:

powers = [2**n for n in range(0,10)]

Here is a more sophisticated example. A currency cross rate is an exchange rate from one currency to another, with an origin currency and a destination currency. We can use our list of US dollar exchange rates to make cross rates for any pair of currencies in the exchange list. For example, if we wanted to set up an exchange from GBP to CNY, we would first convert 1 GBP to 1/0.760425 dollars. We would then convert 1/0.760425 dollars to (1/0.760425)*6.9228 CNY.

Here is a list comprehension that makes a table of all possible cross rates. This is a nested set of list comprehensions, where the outer comprehension uses an inner comprehension to make lists of cross rates, producing a list of lists as the final result.

crosses =[[(o,d,r2/r1) for d,r2 in exchange] for o,r1 in exchange]

Here is one final thing we should do with the resulting table. The diagonal entries represent exchanges where the origin currency and the destination currency are the same. We should go in and set all of those cross rates to be exactly 1. Here is a for loop that can do this.

for i in range(0,len(crosses)): crosses[i][i][2] = 1

Programming assignment

Redo assignment two using tuples. Start your program with the statements

x = [1935,1940,1945,1950,1955,1960,1965,1970,1975,1980] y = [32.1,30.5,24.4,23,19.1,15.6,12.4,9.7,8.9,7.2] data = list(zip(x,y))

and then do everything else in the rest of the program using the data list. Try not to use the x list or the y list in any of the following code: do everything with the data list.

Also, include at least one list comprehesion in your program. The list of residuals is a good candidate for this: try building this list with a list comprehension instead of a loop.

Lists and Tuples store one or more objects or values in a specific order. The objects stored in a list or tuple can be of any type including the nothing type defined by the None Keyword.

Lists and Tuples are similar in most context but there are some differences which we are going to find in this article.

Syntax Differences

Syntax of list and tuple is slightly different. Lists are surrounded by square brackets [] and Tuples are surrounded by parenthesis ().

Example 1.1: Creating List vs. Creating Tuple

list_num = [1,2,3,4] tup_num = (1,2,3,4) print(list_num) print(tup_num)

Output:

[1,2,3,4] (1,2,3,4)

Above, we defined a variable called list_num which hold a list of numbers from 1 to 4.The list is surrounded by brackets []. Also, we defined a variable tup_num; which contains a tuple of number from 1 to 4. The tuple is surrounded by parenthesis ().

In python we have type() function which gives the type of object created.

Example 1.2: Find type of data structure using type() function

type(list_num) type(tup_num)

Output:

list tuple

Mutable List vs Immutable Tuples

List has mutable nature i.e., list can be changed or modified after its creation according to needs whereas tuple has immutable nature i.e., tuple can’t be changed or modified after its creation.

Example 2.1: Modify an item List vs. Tuple

list_num[2] = 5 print(list_num) tup_num[2] = 5

Output:

[1,2,5,4] Traceback (most recent call last): File "python", line 6, in <module> TypeError: 'tuple' object does not support item assignment

In above code we assigned 5 to list_num at index 2 and we found 5 at index 2 in output. Also, we assigned 5 to tup_num at index 2 and we got type error. We can't modify the tuple due to its immutable nature.

Note: As the tuple is immutable these are fixed in size and list are variable in size.

Available Operations

Lists has more builtin function than that of tuple. We can use dir([object]) inbuilt function to get all the associated functions for list and tuple.

Example 3.1: List Directory

dir(list_num)

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Example 3.2: Tuple Directory

dir(tup_num)

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

We can clearly see that, there are so many additional functionalities associated with a list over a tuple.We can do insert and pop operation, removing and sorting elements in the list with inbuilt functions which is not available in Tuple.

Size Comparison

Tuples operation has smaller size than that of list, which makes it a bit faster but not that much to mention about until you have a huge number of elements.

Example 5.1: Calculate size of List vs. Tuple

a= (1,2,3,4,5,6,7,8,9,0) b= [1,2,3,4,5,6,7,8,9,0] print('a=',a.__sizeof__()) print('b=',b.__sizeof__())

Output:

a= 104 b= 120

In above code we have tuple a and list b with same items but the size of tuple is less than the list.

Different Use Cases

At first sight, it might seem that lists can always replace tuples. But tuples are extremely useful data structures

  1. Using a tuple instead of a list can give the programmer and the interpreter a hint that the data should not be changed.
     
  2. Tuples are commonly used as the equivalent of a dictionary without keys to store data. For Example, [('Swordfish', 'Dominic Sena', 2001), ('Snowden', ' Oliver Stone', 2016), ('Taxi Driver', 'Martin Scorsese', 1976)] Above example contains tuples inside list which has a list of movies.
     
  3. Reading data is simpler when tuples are stored inside a list. For example, [(2,4), (5,7), (3,8), (5,9)] is easier to read than [[2,4], [5,7], [3,8], [5,9]]

Tuple can also be used as key in dictionary due to their hashable and immutable nature whereas Lists are not used as key in a dictionary because list can’t handle __hash__() and have mutable nature.

key_val= {('alpha','bravo'):123} #Valid key_val = {['alpha','bravo']:123} #Invalid

Key points to remember:

  1. The literal syntax of tuples is shown by parentheses () whereas the literal syntax of lists is shown by square brackets [] .
  2. Lists has variable length, tuple has fixed length.
  3. List has mutable nature, tuple has immutable nature.
  4. List has more functionality than the tuple.