Python Tuples

In an earlier section, you learned about the Python list. Closely related to the list is something called a tuple. The difference is that a tuple can't be added to after you've set one up. You can't delete items from your tuple, either. They are immutable.

Try this code. First, set up a list:

candidates = ['Anne', 'Ben', 'Claire', 'Davi', 'Elise', 'Frank', 'Gomez', 'Hali']

To set up a tuple, add this line:

final_four = ('Anne', 'Davi', 'Elise', 'Hali')

Note that the items in your tuple go between round brackets. A list goes between square ones. Print the both of them out:

for person in candidates:

print(person)

print("==========")

for finalist in final_four:

print(finalist)

With a list, you can add a candidate on the end:

candidates.append('Idris')

Or you can insert a candidate anywhere you like:

candidates.insert(0, 'Able')

Here, the zero means insert 'Able' at the start of the list. If you wanted to insert an item into, say, the third position, you'd do this:

candidates.insert(2, 'Cara')

Print out your new items to see them displayed:

print("==========")

for person in candidates:

print(person)

However, you can't use append or insert with a tuple. You can use the usual slice operations on a tuple, though:

print("final four 2", final_four[1])
print("Last two: ", final_four[2:])

And you can create a new tuple from the one you already have:

final_two = final_four[1] + final_four[2]
print("FINAL TWO: ", final_two)

 

If you need a data structure that can't be added to or subtracted from, use a tuple. In the next lesson, you'll learn about the Python dicitionary.

Python Dictionaries >