Python Tuple Tutorial: Python Programming for Beginners

In this article, we will explore the concept of the Python tuple – immutable, ordered collections of heterogeneous data.

Knowing how to use Python tuples will prove instrumental not only in how you store data, but will help strengthen your knowledge of the basics of Python programming.

Let’s dive in, find out how they work, and learn how we can start creating a tuple!

Prerequisites: The reader is expected to have familiarity with the Python programming language. An understanding of Python lists will be useful as an analogy.

What are Python Tuples

Tuples are immutable, ordered collections of heterogeneous data in Python.  They are immutable in the sense that once created, they cannot be modified in any way. We will look at a caveat below.  Once declared, the order of elements is fixed. They can contain a mixture of data types. They can also contain duplicate elements.

Below, we will explore their various properties.

Creating Tuples

There are a couple of ways to create tuples. Any set of elements separated by comma default to a tuple. However, it is better to explicitly declare a tuple inside of parentheses as shown below.

A tuple constructor can also be used to create the tuple.

>>> a = 'abc', 123, 555, 555
>>> type(a)
<class 'tuple'>

# parentheses
>>> b = ('abc', 123, 555, 555)
>>> type(a)
<class 'tuple'>

# tuple constructor.
>>> my_tuple3 = tuple((1, 2, 3, 4.5, 'Python'))
>>> my_tuple3[4]
'Python'

Elements of a tuple

Tuples can contain either similar or mixed data types. They can also contain duplicate elements.

# elements of similar type
my_tuple = (1, 2, 2, 3, 4, 5)

# elements of mixed types
my_tuple2 = (1, 'Bob', [3.0, 5.0], 'Barbara')

Indexing Tuples

Tuple elements can be accessed by indexing into the tuple. Let’s use the my_tuple2 tuple declared above.

# the first element (o-based indexing)
>>> my_tuple2[0]
1

# the third element
>>> my_tuple2[2]
[3.0, 5.0]

# the second element of the third element 
>>> my_tuple2[2][1]
5.0

Laptop running code

Slicing/Reversing Tuples

Tuples can be sliced just like lists. Let’s use the my_tuple2 tuple declared above.

# first and second elements
>>> my_tuple2[1:3]
('Bob', [3.0, 5.0])

# second and third elements
>>> my_tuple2[2:4]
([3.0, 5.0], 'Barbara')

# reversing a tuple
>>> my_tuple2[::-1]
('Barbara', [3.0, 6.0], 'Bob', 1)

Iteration

We can use a for-loop to iterate over the elements of my_tuple2.

>>> for elem in my_tuple2 :
...     print (elem)
... 
1
Bob
[3.0, 5.0]
Barbara

Immutability

Tuple cannot be modified i.e. elements cannot be modified or deleted. However, it is important to note that a mutable element of a tuple can be changed.

# updation not supported
>>> my_tuple2[1] = 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

# deletion not supported
>>> del my_tuple2[2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
# updation of the mutable list element is allowed.
>>> my_tuple2
(1, 'Bob', [3.0, 5.0], 'Barbara')
>>> my_tuple2[2][1] = 6.0
>>> my_tuple2
(1, 'Bob', [3.0, 6.0], 'Barbara')

# deleting the whole tuple is allowed
>>> del my_tuple2
>>> my_tuple2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'my_tuple2' is not defined

Tuple Unpacking

The elements of a tuple can be unpacked into variables.

# unpacking
>>> a,b,c, d = (1.0, 3, [6, 7], 'Simon')

>>> a
1.0

>>> b
3

>>> c
[6, 7]

>>> d
'Simon'

sphere

Combining / Repeating Tuples

Tuples can be combined using the + operator. They can also be repeated n times using the (tuple)*n syntax.

# concatenation
>>> [1,2,3] + [4,5,6]
[1, 2, 3, 4, 5, 6]

# repetition
>>> (1,2,3)*3
(1, 2, 3, 1, 2, 3, 1, 2, 3)

Use as key in dictionary (Hashing)

Python dictionaries need keys that are immutable. So a data structure such as a list cannot be a dictionary key. But tuples can be keys of a Python dictionary.

>>> d = {'name' : 'John Doe', 'age': 45, 'city':'Cupertino', 'zip code': 94087}

>>> t = (1,2,3)
>>> d[t] = 'Address 1 Address 2 Address 3'
>>> d
{'name': 'John Doe', 'age': 45, 'city': 'Cupertino', 'zip code': 94087, (1, 2, 3): 'Address 1 Address 2 Address 3'}

Element Count, Position

We can find the number of times an element occurs in a tuple as well as the position(s) of an element in a tuple.

>>> t = (1, 2, 3, 2, 2, 5, 6, 7, 8, 1)

# first index of element in tuple
>>> t.index(2)
1

# all indices of an element in tuple
>>> [index for index, value in enumerate(t) if value == 2]
[1, 3, 4]

# count of element in tuple
>>> t.count(2)
3

Useful Functions

The following functions are useful utility functions to examine the elements of a tuple.

>>> t = (1, 1, 3, 2, 5, 6, 7, 8, 9)

>>> len(t)
9
>>> max(t)
9
>>> min(t)
1

Tuple Membership

The standard Python in operator can be used to check if an element is a member of a tuple. The expression returns True if the element is a member of the tuple and False if it is not.

>>> t = (1, 1, 3, 2, 5, 6, 7, 8, 9)

>>> 5 in t
True

>>> 11 in t
False

Person holding a sticky note that says Python

Additional Reading/References

Want to explore a bit more about creating a Python tuple – or Python Programming in general? Check out the links below!

Conclusion

And that concludes our brief tutorial on the Python tuple. Let’s review some key points:

  • Python tuples are very similar to lists. However, they cannot be modified once created.
  • Their immutability makes them usable as dictionary keys.
  • They can be combined using the + operator and replicated using the * operator.
  • Elements can be packed into a tuple and a tuple can also be unpacked into a set of variables for easy access.
  • They can be indexed into and sliced similar to lists.
  • Elements can be repeated in a tuple.
  • The position of an element(s) and its number of occurrences can be easily ascertained using methods available on the tuple or with a simple list comprehension.

What can we take away from this? Well, you should generally (caveat in the article) use tuples where you need a read-only data structure similar to a list (or any data type that can store multiple items). This ensures that your data is protected, but you can still use that information for a lot of things throughout your program.

Whatever the case may be, understanding this foundational element of the Python programming language is essential and will give you more tools to use as you program with Python. We also encourage you to explore other tuple related subjected like nested tuples, making an empty tuple, tuple packing, and more.

So, we wish you the best of luck out there with your Python projects and hope you find the Python tuple useful!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.