Python Tuples (with Examples)

In Python, Tuples are a data structure of the sequence type that store a collection of data.

Python Tuples have these 5 characteristics.

Here are the characteristics of Python Tuples:


Subscribe to my Newsletter


  • ordered
  • unchangeable
  • immutable
  • allow duplicate value
  • allow values with multiple data types

What is a Python Tuple

A tuple in Python is an immutable sequence type represented by objects separated by commas inside parentheses.

The main advantage to use a Tuple is that it is faster than a list.

What Does it Mean When we Say a Tuple is Immutable

Immutable in Python means that it can’t be changed. Mutable means that they can be changed. Tuples are immutable and lists are mutable.

What are Sequence Types in Python

Sequences types in Python are data types that follow a certain set of characteristics that are unique to sequences. There are three basic sequence types: lists, tuples, and range.

Examples of Python Tuples

Here are a few examples of Python tuples:

  • () – Empty Tuple
  • (1,) – Tuple with a single value
  • (1,2,3) – Tuple containing numeric objects
  • ('hello', 'world') – Tuple containing string objects
  • (True, [1,2], (3,4), 'hello') – Tuple containing multiple objects with different data types

Create a Tuple in Python

There are three ways to create a tuple in Python:

  1. Using Parentheses
  2. Using tuple() constructor
  3. Using Comma-separated values

To create a Python tuple, use the parentheses () with each value separated by a comma.

# Example tuple
t = (1, 2, 3)
t
(1, 2, 3)

A tuple can also be created using the tuple() constructor.

# Tuple constructor
tuple([1,2,3])
(1, 2, 3)

By default, comma-separated values will also return a tuple.

t = 1,2,3
t
(1, 2, 3)

Create a Tuples with Constructor VS Parentheses VS Commas

When creating a tuple it is better to initialize with the parentheses than simple comma-separated values since it makes the code more understandable. Parentheses are more efficient than tuple constructors while constructors are better when creating tuples from iterables.

Show if the Object is a Tuple

To show if a Python object is of the tuple data type, use the type() function on the object.

# Showing the type of a Tuple
t = (1, 2, 3)
type(t)
tuple

Indexing a Tuple

To access an item in a Tuple use the index operator [] starting from 0.

letters = ('a','b','c','d','e')

print(letters[0])
'a'

Slicing a Tuple

To access multiple objects in a Tuple use the index operator [] and the slicing operator :.

letters = ('a','b','c','d','e')

print(letters[:3])
print(letters[1:4])
('a', 'b', 'c')
('b', 'c', 'd')

Python Tuples are Ordered

Python tuples are ordered. Being ordered does not mean that the order is directional (e.g. 1,2,3,…), but simply that the order of the element can’t be changed.

# Simply says that the order will not change
t = (3, 1, 2)
type(t)
tuple

Python Tuples are Immutable

Python tuples are immutable, meaning they can’t be changed.

Can’t Reassign a Value on Tuple

Python tuples are unchangeable. Thus, values of the tuples can’t be reassigned.

# While you can reassign a value on lists
ls = [1, 2, 3]
ls[0] = 2
ls
[2, 2, 3]
# Can't reassign a value on a Tuple
t = (1, 2, 3)
t[0] = 2
TypeError: 'tuple' object does not support item assignment

Can’t be Sorted

Python tuples don’t have the sort method like lists do.

# While you can sort lists
ls = [3, 1, 2]
ls.sort()
ls
[1, 2, 3]
# You can't sort Tuples
t = (3, 1, 2)
t.sort()
AttributeError: 'tuple' object has no attribute 'sort'

You can use the sorted() function on the Tuple, but it will not be returned as a tuple, but as a sorted list.

t = (3, 1, 2)
sorted(t)
[1, 2, 3]

Python Tuples can Have Multiple Data Types

Python tuples can contain various data types.

# Multiple data types
t = (
        1, 
        'hello', 
        ['a', 'b'], 
        dict(a=1,b=2),
        False,
        (1, 2, 3),
    )

print(type(t))
t
<class 'tuple'>
(1, 'hello', ['a', 'b'], {'a': 1, 'b': 2}, False, (1, 2, 3))

How to Create a Tuple with a Single Item

To create a tuple with a single item, open the parentheses, add your item, a comma and close the parenteses (item,).

# Tuple
t = ('hello',)
type(t)
tuple

If you don’t add the comma, you will not create a tuple.

# Not a Tuple
nt = ('hello')
type(nt)
str

Specify a Tuple with a Tuple Constructor

To specify a tuple, use the tuple() constructor function.

# Tuple from list
t = tuple(['hello','world'])
print(type(t))
t
<class 'tuple'>
('hello', 'world')

Specify a Tuple from a String

You can specify a tuple from a string by passing a string to the tuple() constructor function.

# Tuple from string
t = tuple('hello')
t
('h', 'e', 'l', 'l', 'o')

Specify a Tuple from a Dictionary

You can specify a tuple from a dictionary by passing a dictionary object to the tuple() constructor function.

# Tuple from dictionary
d = dict(a=1, b=2, c=3)
t = tuple(d)
t
('a', 'b', 'c')

Create an Empty Python Tuple

You can create an empty tuple by passing no argument to the tuple() constructor function.

# Empty Tuple
t = tuple()
t
()

This is rarely useful, but still can be when you want to always return a tuple even if it were to be empty.

# Almost not useful
def positive_tuples_less_than(x):
    if x <= 0:
        return ()
    else:
        return tuple(range(x))

positive_tuples_less_than(5)
(0, 1, 2, 3, 4)

Iterating Through a Tuple

To iterate through a Python tuple, use a for loop.

letters = ('a','b','c','d','e')
for letter in letters:
    print(letter)
a
b
c
d
e

Check if Item Exist in a Tuple

To check if a specific object exists in a Tuple, use the in operator.

letters = ('a','b','c','d','e')
print('d' in letters)
True

Python Tuples Unpacking

Tuples unpacking is the process of re-assigning tuples values back to Python variables.

# Python tuples unpacking
numbers = (1,2,3)

(a,b,c) = numbers

print(a)
print(b)
print(c)
1
2
3

Tuples Unpacking with the Asterisk (*)

The asterisk next to a tuple variable name is used in for unpacking Python tuples when number of variables is less than the number of values.

# Tuple unpacking using the asterisk
numbers = (1,2,3,4,5)

(one, two, *more_than_three) = numbers

print(one)
print(two)
print(more_than_three)
1
2
[3, 4, 5]

Unpacking Start or Middle Values with the Asterisk

The asterisk can also be used to unpack multiple values in a single variable on variables other than the last.

# Tuple unpacking using the asterisk
numbers = (1,2,3,4,5)

(one, *two_to_last, last) = numbers

print(one)
print(two_to_last)
print(last)

1
[2, 3, 4]
5

How to Zip Tuples Together

Use the zip() function to zip multiple tuples together.

numbers = (1,2,3,4)
letters = ('a','b','c','d')
z_object = zip(numbers, letters)
tuple(z_object)
((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'))

Python Tuple Methods

There are two methods that can be used on tuples: count() and index().

Count()

# Counting Values
t = (1, 2, 3, 3, 3, 4, 3, 4, 5)
t.count(3)
4

Index()

# Getting the index of an element
t = ('a','b','c','d')
t.index('c')
2
# Scanning the tuple from start_index to end_index
t = ('a','b','c','a','c','d')
t.index('c', 3, 5)
4

Functions that can be Used on a Tuple

There are 9 built-in Python functions that can be used on a tuple.

  • all() – Return true if all elements of tuples are true or tuple is empty
  • any() – Return true if any elements of tuples are true and False when tuple is empty
  • enumerate() – Return an enumerate object from the tuple
  • len() – Return the length of the tuple
  • max() – Return the maximum value from the tuple
  • min() – Return the minimum value from the tuple
  • sum() – Return the sum of all values of the tuple
  • sorted() – Return a sorted list of the values of the tuple
  • tuple() – Converts a sequence to a tuple

Difference Between Tuples and Lists in Python

The two main differences between tuples and lists in Python is that tuples are immutable and lists are mutable, and tuples use parentheses instead of square brackets. They are both a sequence of objects separated by a colon.

Why use Tuples Instead of Lists in Python

Tuples are more memory efficient than lists in Python. Since tuples can’t be modified and lists can, lists need to allocate more memory than tuples in case it has to be changed after it has been created.

Advanced Tuples Concepts

How does Tuple Comparison Work in Python?

Tuples in Python are compared position by position.

Take this Tuple comparison for example.

(1,2) < (2,1)
True

The reason why the above is True is because the first item of the first tuple is compared to the first item of the second tuple. If the condition is met on the first item, then the result is returned, otherwise it moves to the other.

(1,2,3) < (1,2,4)
True

Can Tuples Contain Mutable Items?

Yes, tuples can contain mutable items inside them. For example, the tuple (t) below contains a list (a). When we change an item of the list a, the tuple seem to change too.

Does it mean that the tuple is mutable? No

a = [1,2,3]
t = (a, )
print(t)
a[1] = 5
print(t)

The reason for this is that the Python container for the tuple only contains references to the item, when the list inside the tuple changed, the references did not change, and the tuple was did not get notified.

The tuple contains a reference to the list. When you call the tuple, the list gets referred, but the list does not “know” if it is a tuple, a dictionary or any other object that refers to it.

Tuples Swapping

Because Tuples contains references to elements, elements inside them can be swapped, as long as they are external variables.

x = 'a'
y = 1

print('x:', x, 'y:', y)

# Swapping
(x, y) = (y, x)

print('x:', x, 'y:', y)
x: a y: 1
x: 1 y: a

Conclusion

In a nutshell, Python tuples are an immutable data type that can be used to store a collection of values. They are used for data integrity and performance. Tuples also offer indexing and slicing operations, making them very useful in Python programming.

Enjoyed This Post?