Learnmonkey Learnmonkey Logo
× Warning:

The tutorial you are reading is currently a work in-progress.

Python Tuples

What are Tuples?

Tuples are ordered collections of things, just like lists. You can also put any data type you want in a tuple and you can also mix data types. However, you can't change the tuple once you create it. In other words, tuples are immutable.

Making Tuples

It's the same as lists, but we use parentheses (( and )) instead of square brackets. We seperate the items in the tuple by commas. For example:

my_tuple = ("Learnmonkey", 43, True, 314.41)

Getting an Element

To access a tuple element, we type:

tuple[index]

tuple is the name of the tuple variable and index is the index of the element. Indexes start at zero for the first element and go up by one for each element. For example, the element with array index 2 is the third element and the element with array element 4 is the fifth element.

For example:


my_tuple = ("Learnmonkey", 43, True, 314.41)
print(my_tuple[0])
print(my_tuple[2])
print(my_tuple[3])
    

The above code returns:


Learnmonkey
True
314.41

Immutability

As said earlier, tuples are immutable (i.e. you can't change them once you make them). As an example, if we try and do something like:


my_tuple = ("Learnmonkey", 43, True, 314.41)
my_tuple[0] = "Stack Overflow"
    

We get an error:

TypeError: 'tuple' object does not support item assignment

However, this does not mean that we can't change the tuple attached to the tuple variable itself; variables can be changed to whatever we want. The only thing you can't do is to modify the current tuple stored in the variable, like changing the elements or adding and removing elements.