Python Tuples

Tuples in Python are similar to lists in that they can contain multiple values of varying data types, however, tuples are read-only, so once defined, they cannot be changed in any way. Due to this, they must be defined and initialised in one statement. A noticeable difference between a tuple and a list, is that a tuple is defined using parenthesis, whereas a list uses square brackets.

The example below creates a tuple of strings called ‘names’ and initialises it with three values, then, using a ‘for’ loop, displays the names in the console.

names = ("George", "Bob", "Fred")

for name in names:
   print(name)

The output from this will be as follows.

George
Bob
Fred

It is possible to omit the parenthesis when defining and initialising a tuple with no adverse effects.

names = "George", "Bob", "Fred"

Similar to lists, tuples are zero based meaning that the first item in a tuple has an index value of zero and not one. As well as being able to access items in a tuple using a ‘for’ loop, as shown above, the index value can be used to access a single item. The example below outputs the second item in the tuple to the console, which has an index of one.

print(names[1])

A major use of tuples is to pack multiple values in to them with a view of unpacking the values into separate variables at a later point in time. One such example of this is returning multiple values from a function and assigning all the values to separate variables in one statement. Here multiple names are returned from a function and assigned to the variables ‘name1’, ‘name2’ and ‘name3’, which are then displayed to the console, one at a time, producing the same output as shown in the above ‘for’ loop example.

def names():
    return "George", "Bob", "Fred"

name1, name2, name3 = names()

print(name1)
print(name2)
print(name3)

A further similarity that tuples have with lists is that slices can be used to return a specific portion, which is useful where they contain a large number of values.