Accéder au contenu principal

Python Tuples Tutorial

Learn about Python tuples: what they are, how to create them, when to use them, what operations you perform on them and various functions you should know.
7 févr. 2018  · 10 min de lecture

Similar to Python lists, tuples are another standard data type that allows you to store values in a sequence. They might be useful in situations where you might want to share the data with someone but not allow them to manipulate the data. They can however use the data values, but no change is reflected in the original data shared.

In this tutorial, you will see Python tuples in detail:

python tuple tutorial

Be sure to check out DataCamp's Data Types for Data Science course, where you can consolidate and practice your knowledge of data structures such as lists, dictionaries, sets, and many more! Alternatively, also check out this Python Data Structures Tutorial, where you can learn more about the different data structures that Python uses.

Python Tuple

As you already read above, you can use this Python data structure to store a sequence of items that is immutable (or unchangeable) and ordered.

Tuples are initialized with () brackets rather than [] brackets as with lists. That means that, to create one, you simply have to do the following:

cake = ('c','a','k','e')
print(type(cake))
<class 'tuple'>

Remember that the type() is a built-in function that allows you to check the data type of the parameter passed to it.

Tuples can hold both homogeneous as well as heterogeneous values. However, remember that once you declared those values, you cannot change them:

mixed_type = ('C',0,0,'K','I','E')

for i in mixed_type:
    print(i,":",type(i))
C : <class 'str'>
0 : <class 'int'>
0 : <class 'int'>
K : <class 'str'>
I : <class 'str'>
E : <class 'str'>
# Try to change 0 to 'O'
mixed_type[1] = 'O'
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-16-dec29c289a95> in <module>()
----> 1 mixed_type[1] = 'O' # Trying to change 0 to 'O'


TypeError: 'tuple' object does not support item assignment

You get this last error message because you can not change the values inside a tuple.

Here is another way of creating a tuple:

numbers_tuple = 1,2,3,4,5
print(type(numbers_tuple))
<class 'tuple'>

Master your data skills with DataCamp

More than 10 million people learn Python, R, SQL, and other tech skills using our hands-on courses crafted by industry experts.

Start Learning
learner-on-couch@2x.jpg

Tuples versus Lists

As you might have noticed, tuples are very similar to lists. In fact, you could say that they are immutable lists which means that once a tuple is created you cannot delete or change the values of the items stored in it. You cannot add new values either. Check this out:

numbers_tuple = (1,2,3,4,5)
numbers_list = [1,2,3,4,5]

# Append a number to the tuple
numbers_tuple.append(6)
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-26-e47776d745ce> in <module>()
      3 
      4 # Append a number to the tuple
----> 5 numbers_tuple.append(6)


AttributeError: 'tuple' object has no attribute 'append'

This throws an error because you cannot delete from or append to a tuple but you can with a list.

# Append numbers to the list
numbers_list.append(6)
numbers_list.append(7)
numbers_list.append(8)

# Remove a number from the list
numbers_list.remove(7)
print(numbers_list)
[1, 2, 3, 4, 5, 6, 8]

But why would you use tuples if they are immutable?

Well, not only do they provide "read-only" access to the data values but they are also faster than lists. Consider the following pieces of code:

import timeit
timeit.timeit('x=(1,2,3,4,5,6,7,8,9)', number=100000)
0.0018976779974764213
timeit.timeit('x=[1,2,3,4,5,6,7,8,9]', number=100000)
0.019868606992531568

What does immutable really mean with regards to tuples?

According to the official Python documentation, immutable is 'an object with a fixed value', but 'value' is a rather vague term, the correct term for tuples would be 'id'. 'id' is the identity of the location of an object in memory.

Let's look a little more in-depth:

# Tuple 'n_tuple' with a list as one of its item.
n_tuple = (1, 1, [3,4])

#Items with same value have the same id.
id(n_tuple[0]) == id(n_tuple[1])
True
#Items with different value have different id.
id(n_tuple[0]) == id(n_tuple[2])
False
id(n_tuple[0])
4297148528
id(n_tuple[2])
4359711048
n_tuple.append(5)
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-40-3cd258e024ff> in <module>()
----> 1 n_tuple.append(5)


AttributeError: 'tuple' object has no attribute 'append'

We cannot append item to a tuple, that is why you get an error above. This is why tuple is termed immutable. But, you can always do this:

n_tuple[2].append(5)
n_tuple
(1, 1, [3, 4, 5])

Thus, allowing you to actually mutate the original tuple. How is the tuple still called immutable then?

This is because, the id of the list within the tuple still remains the same even though you appended 5 to it.

id(n_tuple[2])
4359711048

To sum up what you have learnt so far:

Some tuples (that contain only immutable objects: strings, etc) are immutable and some other tuples (that contain one or more mutable objects: lists, etc) are mutable. However, this is often a debatable topic with Pythonistas and you will need more background knowledge to understand it completely. This is a more in-depth article for the same. For now, lets just say tuples are immutable in general.

  • You can't add elements to a tuple because of their immutable property. There's no append() or extend() method for tuples,
  • You can't remove elements from a tuple, also because of their immutability. Tuples have no remove() or pop() method,
  • You can find elements in a tuple since this doesn't change the tuple.
  • You can also use the in operator to check if an element exists in the tuple.

So, if you're defining a constant set of values and all you're going to do with it is iterate through it, use a tuple instead of a list. It will be faster than working with lists and also safer, as the tuples contain "write-protect" data.

If you want to know more about Python lists, make sure to check out this tutorial!

Common Tuple Operations

Python provides you with a number of ways to manipulate tuples. Let's check out some of the important ones with examples.

Tuple Slicing

The first value in a tuple is indexed 0. Just like with Python lists, you can use the index values in combination with square brackets [] to access items in a tuple:

numbers = (0,1,2,3,4,5)
numbers[0]
0

You can also use negative indexing with tuples:

numbers[-1]
5

While indexing is used to obtain individual items, slicing allows you to obtain a subset of items. When you enter a range that you want to extract, it is called range slicing. The general format of range slicing is:

[Start index (included):Stop index (excluded):Increment]

Here Increment is an optional parameter, and by default the increment is 1.

# Item at index 4 is excluded
numbers[1:4]
(1, 2, 3)
# This provides all the items in the tuple
numbers[:]
(0, 1, 2, 3, 4, 5)
# Increment = 2
numbers[::2]
(0, 2, 4)

Tip: You can also use the negative increment value to reverse the tuple.

numbers[::-1]
(5, 4, 3, 2, 1, 0)

Tuple Addition

You can combine tuples to form a new tuple. The addition operation simply performs a concatenation with tuples.

x = (1,2,3,4)
y = (5,6,7,8)

# Combining two tuples to form a new tuple
z = x + y 

print(z)
(1, 2, 3, 4, 5, 6, 7, 8)
y = [5,6,7,8]
z = x + y
print(z)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-55-d352c6414a4c> in <module>()
      1 y = [5,6,7,8]
----> 2 z = x + y
      3 print(z)


TypeError: can only concatenate tuple (not "list") to tuple

You can only add or combine same data types. Thus combining a tuple and a list gives you an error.

Tuple Multiplication

The multiplication operation simply leads to repetition of the tuple.

x = (1,2,3,4)
z = x*2
print(z)
(1, 2, 3, 4, 1, 2, 3, 4)

Tuple Functions

Unlike Python lists, tuples does not have methods such as append(), remove(), extend(), insert() and pop() due to its immutable nature. However, there are many other built-in methods to work with tuples:

count() and len()

count() returns the number of occurrences of an item in a tuple.

a = [1,2,3,4,5,5]
a.count(5)
2

With the len() function, you can returns the length of the tuple:

a = (1,2,3,4,5)
print(len(a))
5

any()

You can use any() to discover whether any element of a tuple is an iterable. You'll get back True if this is the case, else it will return False.

a = (1,)
print(any(a))
True

Notice the , in the declaration of the tuple a above. If you do not specify a comma when initializing a single item in a tuple, Python assumes that you mistakenly added an extra pair of bracket (which is harmless) but then the data type is not a tuple. So remember to add a comma when declaring a single item in a tuple.

Now, back to the any() function: In a boolean context, the value of an item is irrelevant. An empty tuple is false, any tuple with at least one item is true.

b = ()
print(any(b))
False

This function might be helpful when you are calling a tuple somewhere in your program and you want to make sure that the tuple is populated.

tuple()

Use tuple() to converts a data type to tuple. For example, in the code chunk below, you convert a Python list to a tuple.

a_list = [1,2,3,4,5]
b_tuple = tuple(a_list)
print(type(b_tuple))
<class 'tuple'>

min() and max()

While max() returns the largest element in the tuple, you can use min() to return the smallest element of the tuple. Consider the following example:

print(max(a))
print(min(a))
5
A

You can also use this with tuples containing string data type.

# The string 'Apple' is automatically converted into a sequence of characters. 
a = ('Apple') 
print(max(a))
p

sum()

With this function, you return the total sum of the items in a tuple. This can only be used with numerical values.

sum(a)
28

sorted()

To return a tuple with the elements in an sorted order, use sorted(), just like in the following example:

a = (6,7,4,2,1,5,3)
sorted(a)
[1, 2, 3, 4, 5, 6, 7]

It is worth noting that the return type is a list and not a tuple. The sequence in the original tuple 'a' is not changed and the data type of 'a' still remains tuple.

Bonus: Assigning Multiple Values

Something cool that you can do with tuples is to use them to assign multiple values at once. Check this out:

a = (1,2,3)
(one,two,three) = a
print(one)
1

a is a tuple of three elements and (one,two,three) is a tuple of three variables. Assigning (one,two,three) to a tuple assigns each of the values of a to each of the variables: one, two and three, in order. This can be handy when you have to assign a range of values to a sequence stored in a tuple.

Congrats!

You have made it to the end of this tuple tutorial! Along the road, you learned more about what Python tuples are, how you can initialize them, what the most common operations are that you can do with them to manipulate them and what the most common methods are so that you can get more insights from these Python data structures. As a bonus, you learned that you can also assign multiple values to tuples at once.

Sujets

Python Courses

cours

Introduction to Python

4 hr
5.5M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
Afficher les détailsRight Arrow
Commencer Le Cours
Voir plusRight Arrow
Apparenté

didacticiel

Tuples in Python Tutorial

Learn to use and unpack Tuples in Python.
DataCamp Team's photo

DataCamp Team

3 min

didacticiel

Python Sets and Set Theory Tutorial

Learn about Python sets: what they are, how to create them, when to use them, built-in functions and their relationship to set theory operations.
DataCamp Team's photo

DataCamp Team

13 min

didacticiel

Python Dictionaries Tutorial

Learn how to create a dictionary in Python.
DataCamp Team's photo

DataCamp Team

3 min

didacticiel

Python List Functions & Methods Tutorial and Examples

Learn about Python List functions and methods. Follow code examples for list() and other Python functions and methods now!
Abid Ali Awan's photo

Abid Ali Awan

7 min

didacticiel

Python Descriptors Tutorial

Learn what Python Descriptors are, when you should use them, and why you should use them.
Aditya Sharma's photo

Aditya Sharma

13 min

didacticiel

Python Functions: How to Call & Write Functions

Discover how to write reusable and efficient Python functions. Master parameters, return statements, and advanced topics like lambda functions. Organize your code better with main() and other best practices.
Karlijn Willems's photo

Karlijn Willems

14 min

See MoreSee More