Python Tuples – The immutable sequence of objects

In this Python tuples tutorial, we are going to look at another data structure that is Tuples. First, we will see what tuples are, then we will discuss how to create, access, slice and delete elements in the tuple. Furthermore, we will see the functions and operations performed on tuples.

What are Tuples in Python?

Tuples are collections of Python objects. They are similar to lists but the difference between them is that tuples are immutable while lists are mutable.

Learn to store multiple values in Python using TechVidvan’s Python Lists article.

How to Create Tuples in Python?

Tuples are created by typing a sequence of items, separated by commas. Optionally, you can put the comma-separated values in parenthesis.

Tuple1 = (1,2,5,6)
Tuple2 = (‘a’, “b”, ‘c’, “d”)
Tuple3 = () #empty tuple
Tuple4 = 5,3,1
Tuple5 = (“London”, “Tokyo”, “Korea”, 1986,1640, 1948)

Note: To create a single item tuple, you have to use a comma after the value.

Example:

Tup1 = (5)
Tup2 = (5,)
print(type(Tup1))
print(type(Tup2))

Output:

<class ‘int’>
<class ‘tuple’>

Accessing Tuple

The values of tuples are stored at different index positions starting from zero. We can access the values by using their index positions inside square brackets.

Code:

cars = (“Ferrari”, “BMW”, “Audi”, “Jaguar”)
print(cars)
print(cars[0])
print(cars[1])
print(cars[3])
print(cars[3])
print(cars[4])

Output:

(“Ferrari”, “BMW”, “Audi”, “Jaguar”)
Ferrari
BMW
Audi
Jaguar
Traceback (most recent call last):
  File “<stdin>”, line 7, in <module>
IndexError: tuple index out of range

We got the index error in line number 7 because index 4 is out of the range.

Iterating over Tuples

We can use for loops to iterate on a tuple. The for loop will keep on iterating until the elements in the tuples are exhausted.

for num in (12,4,6,22,8,10):
    print(num)

Output:

12
4
6
22
8
10

Slicing Tuples

To take out some parts from the tuple, we use the slicing operator([]) and it returns a new tuple.

1. Positive Indexing

In positive indexing, we traverse the list from left to right. As we know, the index starts from zero and goes till the number of elements minus one.

Code:

numbers = (1,2,3,4,5,6)

#From zero to 4th element
print( numbers[:4] )
#From 2nd to 3rd element
print( numbers[1:3] )
#From 5th to 5th element
print( numbers[4:5] )

Output:

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

2. Negative Indexing

In negative indexing, we traverse from right to left.

The last number is accessed with -1, the second number with -2 and so on.

Code:

numbers = (1,2,3,4,5,6)

print( numbers[-3:] )
print( numbers[:-3] )
print( numbers[2:-2] )
print( numbers[-6:-2] )

Output:

(4,5,6)
(1,2,3)
(3,4)
(1,2,3,4)

Tuples Unpacking

With a special syntax, Python can unpack the values of a tuple and extract them into single variables.

Let’s see this with an example,

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

Output:

1
2
3

The number of variables to the left and right side should be the same and it assigns each variable respectively.

Changing Tuple Values

As we said earlier that tuples are immutable which means that once a tuple is created we cannot change its value.

Let’s try changing a tuple value and see what error we get.

Code:

num = (1,2,3)
num[1] = 20

Output:

Traceback (most recent call last):
  File “<stdin>”, line 2, in <module>
TypeError: ‘tuple’ object does not support item assignment

Let’s see a special case when a tuple is containing list inside it. Lists are mutable so we can change the list value inside the tuples.

Code:

tup = (‘a’, ’b’, [1, 2, 3], ’c’, ’d’)
tup[2][1] = 10
print(tup)

Output:

(‘a’, ’b’, [1, 10, 3], ’c’, ’d’)

Deleting Python Tuples

Tuples are immutable objects so we cannot change or modify tuples. So, what about deleting an element from the tuple?

tup = (1,2,3,4,5)
del tup[2]

Output:

Traceback (most recent call last):
  File “<stdin>”, line 2, in <module>
TypeError: ‘tuple’ object doesn’t support item deletion

Hence now we conclude that we cannot delete an element from the tuple.

But we can delete the whole tuple.

del tup
print(tup)

Output:

Traceback (most recent call last):
  File “<stdin>”, line 2, in <module>
NameError: name ‘tup’ is not defined

Python Tuple Operations

Let’s see the operations we can perform on tuples. Tuples can be concatenated and repeated, they return a new tuple after operations.python tuple operations

Python Tuple Methods

Since tuples are immutable, we don’t have methods to add or remove items. Instead, we have two available methods, count() and index().

1. count()

This method is used to count the number of occurrences of a Python object in the tuple. It returns an integer value.

(1,2,2,2,1,4,2).count(2)

Output:

4

2. index()

This method returns the index of the specified item. In the case of multiple occurrences, it returns the first position of the object.

(1, 3, 5, 7, 9, 7).index(7)

Output:

3

Python Tuple Functionspython tuple functions

1. len()

The len() function returns us the length of a sequence or a container. It is applicable on tuples also.

len((1,2,3,4,5))

Output:

5

2. max()

The max() function returns us the maximum element from a sequence or container. The elements must contain all numbers or all characters.

max((120,20,240))

Output:

240

3. min()

The min() function returns the minimum value from group of elements.

min((-10,-5, 3,20))

Output:

-10

4. sum()

The sum() function calculates the total sum of all elements and returns it. It can only be used on numeric values.

sum((5,10,15,20))

Output:

50

5. tuple()

The tuple() function converts an iterable like a list, set, string into an immutable tuple.

tuple([1,2,3,4])

Output:

(1,2,3,4)

6. sorted()

The sorted() function sorts the elements in ascending order. It takes an iterable like a tuple and returns a list of sorted elements.

sorted((4,3,2,1))

Output:

[1,2,3,4]

That’s all about the Python tuples.

Summary

In this TechVidvan’s Python tuples article, we studied the tuple data structure in Python. We learned how to create tuples and indexing of tuples.

Time to clear your concepts of data structures in Python with TechVidvan.

Tuples are immutable so we use them when we don’t want to change the values of an object. Later on, we saw how to access elements of tuples and all the functions and operations that we can use on tuples.

If you have any queries in TechVidvan’s Python tuples article, mention them in the comment section.

Happy Learning!!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.