Back

Tuples

Introduction
A tuple is similar to a list, except that when we create a tuple, we use normal brackets (parentheses) instead of square brackets. Like a list, each tuple is given a name. It contains a set of items, the items have an order and the first item is at position zero. The big difference between a list and a tuple is that a tuple is 'immutable'. That simply means that you cannot change it in any way once you have created it. Lists have methods like insert(), remove(), append(), extend() and so on. Tuples do not have these kinds of methods because they would change the tuple.

Here are some examples of tuples being created. We have also printed out one tuple, one element in a tuple, and used some of Python's built-in functions for tuples.

letters = ('a', 'b', 'c')
nums = (10, 20, 30, 40, 50)
empty = ()
bigList = (34.5, True, letters, nums, empty)

for item in bigList:
    print (item)

print (letters[1])
print (max(nums))

print (min(nums))
print (len(bigList))

The functions we used above did not change the tuple in any way. If we tried to add a tuple or remove one like we did for lists, we will run into trouble. Try adding this code and see what happens:

print (nums.append(60)) and then try

print (nums.remove(20))

You will have got error messages.

Special case
There is a special case you should be aware of with tuples. If a tuple has just one element in it when you create it, you must follow it with a comma, like this:

singleValue = (56,)
oneMore = ("David",)

Creating a list from a tuple
If you did need to modify a value in a tuple, you can't directly because they immutable. What you can do is to create a list from a tuple and then use that. Here's an example you can add to your existing code:
 

newList = list(nums)
newList.append(60)
for item in newList:
    print (item) 

Why use tuples?
Although tuples may seem similar to lists and may seem less powerful to lists because you can't modify them in any way, they do have their uses. Tuples are faster than lists. If you have to traverse through a set of constants, for example, you would want to use a tuple rather than a list to do this because accessing and reading from the tuple will be faster. Data that doesn't need to change (like constants) can be protected from any possibility of change by putting them in a tuple. 

The best way of understanding tuples is to write code and use them. We have created some exercises using tuples in our Python course on this web site to help get you started.

Back