Python Tuples

Summary: in this tutorial, you’ll learn about Python tuples and how to use them effectively.

Introduction to Python tuples

Sometimes, you want to create a list of items that cannot be changed throughout the program. Tuples allow you to do that.

A tuple is a list that cannot change. Python refers to a value that cannot change as immutable. So by definition, a tuple is an immutable list.

Defining a tuple

A tuple is like a list except that it uses parentheses () instead of square brackets [].

The following example defines a tuple called rgb:

rgb = ('red', 'green', 'blue')Code language: Python (python)

Once defining a tuple, you can access an individual element by its index. For example:

rgb = ('red', 'green', 'blue')

print(rgb[0])
print(rgb[1])
print(rgb[2])Code language: Python (python)

Output:

red
green
blueCode language: Python (python)

Since a tuple is immutable, you cannot change its elements. The following example attempts to change the first element of the rgb tuple to 'yellow':

rgb = ('red', 'green', 'blue')
rgb[0] = 'yellow'Code language: Python (python)

And it results in an error:

TypeError: 'tuple' object does not support item assignmentCode language: Python (python)

Defining a tuple that has one element

To define a tuple with one element, you need to include a trailing comma after the first element. For example:

numbers = (3,)
print(type(numbers))Code language: Python (python)

Output:

<class 'tuple'>Code language: Python (python)

If you exclude the trailing comma, the type of the numbers will be int , which stands for integer. And its value is 3. Python won’t create a tuple that includes the number 3:

numbers = (3)
print(type(numbers))Code language: Python (python)

Output:

<class 'int'>Code language: Python (python)

Assigning a tuple

Even though you can’t change a tuple, you can assign a new tuple to a variable that references a tuple. For example:

colors = ('red', 'green', 'blue')
print(colors)

colors = ('Cyan', 'Magenta', 'Yellow', 'black')
print(colors)Code language: Python (python)

Summary

  • Tuples are immutable lists.
  • Use tuples when you want to define a list that cannot change.
Did you find this tutorial helpful ?