Python Tuples

Outside Resources:

Tutorials Point Tuples

w3schools Tuples


Tuples are similar to lists.

Tuples use (parentheses) while lists use [square brackets].

The big difference is that tuples areĀ immutable. This means that after you create the tuple, you can’t change one individual value.

Example that works with lists, but not with tuples:

my_list = [42, 3.14, 2.718]
#reassign item 2: works with lists
my_list[2] = 100

my_tuple = (42, 3.14, 2.718)
#this command isn't allowed for a tuple
my_tuple[2] = 100

If you want to change part of a tuple, you need to recreate the whole thing:

#create the tuple again with the new value
my_tuple = (42, 3.14, 100)

Other than being immutable, tuples work like lists. They can be sliced, looped through, and so on. Sometimes it doesn’t matter whether you use a loop or a tuple, but in other cases a Python function only works if the input is a tuple.