Python Basics: Tuples

Ventsislav Yordanov
Towards Data Science
7 min readFeb 7, 2019

--

Source: https://www.quora.com/Can-you-suggest-some-good-books-websites-for-learning-Python-for-a-layman

After reading this blog post you’ll know:

  • What is the tuple data type in Python
  • How to initialize tuples
  • How to iterate over tuples
  • Common sequence operations over tuples
  • What is tuple unpacking
  • What’s the difference between tuples and lists

Introduction

Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in).

Sequences are a very common type of iterable. Some examples for built-in sequence types are lists, strings, and tuples. They support efficient element access using integer indices and define a method that returns the length of the sequence.

Objects whose value can change are said to be mutable. Objects whose value is unchangeable once they are created are called immutable.

If you want more details about sequences and immutable objects in Python you can check my previous blog posts:

Tuples look similar to lists. They can contain multiple values. The main difference between lists and tuples is that the tuples are immutable, while the lists are mutable.

Tuples Initialization

In Python, we can initialize a tuple in several ways

  • Using a pair of parentheses to denote an empty tuple: ()
  • Using a trailing comma for a tuple with one value: a, or (a,)
  • Separating items with commas: a, b, c or (a, b, c)
  • Using the tuple() built-in: tuple() or tuple(iterable)

The parentheses are optional except in the empty tuple case, or when they are needed to avoid syntactic ambiguity. For example, f(a, b) is a function call with two arguments, while the f((a, b)) is a function call with one argument passed as a tuple of two elements.

Initializing Empty Tuples

Output:

<class 'tuple'>
<class 'tuple'>

()
()

Initializing Tuples with a Single Value

Output:

<class 'tuple'>
<class 'tuple'>

('Python',)
('Data Science',)

Initializing Tuples with Multiple Values

Output:

<class 'tuple'>
<class 'tuple'>

(1, 2, 3)
(1, 2, 3)

Initializing Tuples from Iterables

Output:

<class 'tuple'>
('Python', 'Maths', 'Machine Learning')

Iterate over Tuples

We already know that tuples are sequence data type and we can iterate over sequences because they’re iterable.

Output:

Pineapple
orange
banana
apple

Enumerate

The enumerate(iterable, start=0) built-in function in Python returns an iterator. When we iterate over this iterator it returns a tuple containing a count (starts from 0) and the values obtained from iterating over iterable.

Output:

0 Pineapple
1 orange
2 banana
3 apple

0 pandas
1 scikit-learn
2 seaborn

Common Sequence Operations

In Python, we have some common sequence operations that are supported by most sequence types, both mutable and immutable.

This table lists the sequence operations sorted in ascending priority. In the table, s and t are sequences of the same type, n, i, j and k are integers and x is an arbitrary object that meets any type and value restrictions imposed by s.

The in and not in operations have the same priorities as the comparison operations. The + (concatenation) and * (repetition) operations have the same priority as the corresponding numeric operations.

Source: https://docs.python.org/3/library/stdtypes.html#typesseq-common

Let’ see how we can do these operations on tuples.

in, not in

Output:

True
False

False
True

Concatenation

Output:

('Python', 'Web Development', 'Machine Learning', 'Communication', 'Courtesy', 'Flexibility', 'Integrity')

Multiplication

Output:

(['Communication', 'Courtesy'], ['Communication', 'Courtesy'], ['Communication', 'Courtesy'])

This is equivalent to adding soft_skills to itself three times. However, be careful! The items in the soft_skills are not copied, they’re referenced multiple times. Let’s see what will happen if we add value to the first list of the tuple.

Output:

(['Communication', 'Courtesy'], ['Communication', 'Courtesy'], ['Communication', 'Courtesy'])

(['Communication', 'Courtesy', 'Responsibility'], ['Communication', 'Courtesy', 'Responsibility'], ['Communication', 'Courtesy', 'Responsibility'])

The new added value is added to the three lists because they’re referencing to the same object.

Indexing

Output:

Communication
Responsibility

Yes, in Python we can use negative indexes (we can get the last element using -1 as an index). When we use a negative index, this formula is applied to calculate the actual index: len(sequence) + index.

In our case, the length is 5, so we get the item at index 5 — 1 = 4 and that’s the Responsibility item.

Slicing

We can use slicing to select a range of items in a sequence object. The syntax is sliceable[start_index:end_index:step].

  • The start_index is the beginning index of the slice, the element at this index will be included to the result, the default value is 0.
  • The end_index is the end index of the slice, the element at this index will not be included to the result. The default value is the len(sequence).
  • The step is the amount by which the index increases,
    the default value is 1. If we set a negative value for the step, we’ll move backward.

Output:

('Courtesy', 'Flexibility', 'Integrity')
('Communication', 'Courtesy', 'Flexibility', 'Integrity')
('Communication', 'Courtesy', 'Flexibility', 'Integrity', 'Responsibility')
('Communication', 'Flexibility', 'Responsibility')
('Responsibility', 'Integrity', 'Flexibility', 'Courtesy', 'Communication')

min, max, and len

We can use the min(), max() and len() built-in function to get the maximum value, minimum values and the length of a sequence.

Output:

5
Communication
Responsibility

11
7
90

Index and Count

We have available the index and count methods for tuples. We can use the first one to identify the index of a given value and the second one to identify how much times we have this value in our tuple.

Output:

1--------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-21-f2447af847ce> in <module>()
3
4 numbers = (10, 22, 53, 53, 8, 9, 11, 45, 90, 7, 26)
----> 5 print(numbers.index(100))

ValueError: tuple.index(x): x not in tuple

We can see that if we pass a value which is not in our tuple, we’ll get a ValueError.

Output:

1
2

0

If we pass a value which doesn’t exist in our tuple the count method will return 0. This time there is no error.

Tuple Unpacking

We can also “unpack” values from a tuple into variables. Also, the more general approach is called sequence unpacking, so this will work for any sequence. We already saw that with the enumerate built-in function example.

Output:

10
20
30

Note that when unpacking a tuple the number of variables on the left side should be equal to the number of the values in the tuple. Otherwise, we’ll get an error.

Output:

--------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-45-282b018b9602> in <module>()
----> 1 a, b = (10, 20, 30)

ValueError: too many values to unpack (expected 2)

Output:

--------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-43-c91a3d9d3fc4> in <module>()
----> 1 a, b,c,d = (10, 20, 30)

ValueError: not enough values to unpack (expected 4, got 3)

Tuples vs Lists

As we said earlier, the main difference between lists and tuples is that the tuples are immutable, while the lists are mutable.

Important notes:
The value of an immutable container that contains a reference to a mutable object can be changed if that mutable object is changed. When we talk about the mutability of a container only the identities of the contained objects are implied. However, if our immutable container contains only immutable data types, its value cannot be changed. See examples in this blog post.

Unlike lists, tuples don’t have methods such as append(), insert(), remove(), pop(), and extend() because of their immutable nature.

Output:

['Flexibility', 'Courtesy', 'Flexibility', 'Integrity', 'Responsibility']--------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-47-5d2973b1f2b4> in <module>()
4
5 tuple_skills = ("Communication", "Courtesy", "Flexibility", "Integrity", "Responsibility")
----> 6 tuple_skills[0] = "Flexibility"

TypeError: 'tuple' object does not support item assignment

Additional Notes from the Docs

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

Source: https://docs.python.org/3.7/tutorial/datastructures.html#tuples-and-sequences

When to Use Tuples

  • Tuples are faster than lists. If you need a constant set of values and all you need to do with it is iterating through it, use a tuple instead of a list.

Output:

0.034131127635760095
0.11737610517116082

The timeit library allows us to measure the elapsed time in seconds. We can clearly see that the tuple initializations are faster than the list initializations.

  • Tuples which contain only immutable values can be used as keys for a dictionary, while lists cannot.

Output:

Introducton--------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-c18ababebf4d> in <module>()
2 print(book[(1, 10)])
3
----> 4 book = {[1, 10]: "Introducton", [11, 15]: "Notation and Definitions", [16, 30]: "Fundamental Algorithms"}

TypeError: unhashable type: 'list'
  • Where our tuples contain only immutable objects, we can use them to ensure that our data will be not changed.

Summary

  • Tuples are immutable sequences, typically used to store collections of heterogeneous data (such as the 2-tuples produced by the enumerate() built-in).
  • The main difference between lists and tuples is that the tuples are immutable, while the lists are mutable.
  • We can initialize a tuple using a pair of parentheses () and values inside separated with commas.
  • We can initialize a tuple using the tuple(iterable) built-in function.
  • We can iterate over tuples using a simple for-loop.
  • We can do common sequence operations on tuples like indexing, slicing, concatenation, multiplication, getting the min, max value and so on.
  • We can unpack values from a tuple
  • Use a tuple instead of a list when you need a constant set of values and all you need to do with it is iterating through it.

Newsletter

If you want to be notified when I post a new blog post you can subscribe to my newsletter.

LinkedIn

Here is my LinkedIn profile in case you want to connect with me. I’ll be happy to be connected with you.

Final Words

Thank you for the read. I hope that you have enjoyed the article. If you like it, please hold the clap button and share it with your friends. I’ll be happy to hear your feedback. If you have some questions, feel free to ask them. 😉

Resources

--

--