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 change 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 = ('red', 'green', 'blue')
Once you define a tuple, you can access an individual element by each element’s index, just like a list. For example:
rgb = ('red', 'green', 'blue') print(rgb) print(rgb) print(rgb)
red green blue
Since a tuple is immutable, you cannot change its elements. The following attempts to change the first element of the
rgb tuple to
rgb = ('red', 'green', 'blue') rgb = 'yellow'
And it results int this error:
TypeError: 'tuple' object does not support item assignment
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))
If you include the trailing comma,
numbers will be 3. It won’t create a tuple that includes the number 3:
numbers = (3) print(type(numbers))
Assigning a tuple
Even though you can’t change a tuple, you can assign a new tuple to a variable that represents a tuple.
colors = ('red', 'green', 'blue') print(colors) colors = ('Cyan', 'Magenta', 'Yellow', 'black') print(colors)
- Tuples are immutable lists.
- Use tuples when you want to define list that cannot change.