Python Tuples

FREE Online Courses: Elevate Your Skills, Zero Cost Attached - Enroll Now!

We will learn about one of the data structures, called tuples, in this article. Wondering why we need tuples when we already have lists?

We will learn about creating tuples, accessing their elements, their properties, methods on tuples, etc. So let’s start.

What is Tuple in Python?

Tuples are the sequences of values of different data types. It is

  • Ordered
  • Immutable
  • Allows duplicate values.

Creating tuple in Python

The elements of a tuple are enclosed between circular brackets, (), with each element separated by a comma.

1. Creating an empty Python tuple:

To create an empty tuple we just need to assign the square brackets to the variable as shown below. We can use the type() function to check the data type.

Example of creating an empty tuple in Python:

tup1=()
print("The type of", tup1,"is:", type(tup1))

Output:

The type of () is: <class ‘tuple’>

2. Creating Python tuple with single element:

To create a tuple with a single element, we need to add a comma after the element. If we don’t add the comma, it will be assumed as the data type of that element. The below code shows this.

Example of creating python tuple with a single element:

tup2=(4)
print("The type of", tup2,"is:", type(tup2))

tup3=(4,)
print("The type of", tup3,"is:", type(tup3))

Output:

The type of 4 is: <class ‘int’>

The type of (4,) is: <class ‘tuple’>

3. Creating Python tuple with multiple elements:

We can create a tuple with multiple elements by separating the elements by comma and enclosing them between circular parentheses. We don’t need to add a comma at the end like in the case of a single element.

It can also contain different values of different data types, including lists, tuples, etc. For example,

Example of creating tuple in Python with multiple element:

tup4 = ('a','e','i','o','u')
print("The type of", tup4,"is:", type(tup4))

tup5=(3,9.0,'a',"PythonGeeks",4.5)
print("The type of", tup5,"is:", type(tup5))

tup=(1,4,['a','b'],(4.5,8))
print("The type of", tup,"is:", type(tup))

Output:

The type of (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) is: <class ‘tuple’>

The type of (3, 9.0, ‘a’, ‘PythonGeeks’, 4.5) is: <class ‘tuple’>

The type of (1, 4, [‘a’, ‘b’], (4.5, 8)) is: <class ‘tuple’>

4. Packing in Python

Packing is a method of creating a tuple without using parentheses. The below example shows a way of creating tuples with single and multiple elements by packing.

Example of creating Python tuple with multiple elements:

tup6='a',
print("The type of", tup6,"is:", type(tup6))

tup7=4,9.4,'t',"Python"
print("The type of", tup7,"is:", type(tup7))

Output:

The type of (‘a’,) is: <class ‘tuple’>

The type of (4, 9.4, ‘t’, ‘Python’) is: <class ‘tuple’>

Accessing elements of tuples in Python

Since tuples are ordered, we can access the elements of a tuple using indexing. Similar to the lists, here the indexing starts from zero. That is, the first element has an index of 0.

1. Accessing single element in Python Tuple:

To access an element from a list we can write the tuple name followed by the index in square brackets. We can also give negative indexing, where the first element from the right has the index -1. And this reduces as we go to the left.

Example of accessing an element from Python tuple:

tup=(5,8.4,'j',(3,4.7),['r',7.9])
print("tup[0]:",tup[0]) #accessing the first element

print("tup[-2]:",tup[-2]) #accessing the last second element

Output:

tup[0]: 5

tup[-2]: (3, 4.7)

2. Accessing multiple elements in Python Tuples:

We can again use indexing to access multiple elements. These are the following cases encountered to get more than one element:

a. To get the elements from index i to j, excluding the jth, we give “i:j” indexing.
b. To get all the elements from the index i, we give “i:” indexing.
c. To get all the elements before index i, excluding the ith, we give “:i” indexing.

This method is called slicing. The values of i and j can be positive or negative. For more understanding look at the below example.

Example of accessing multiple elements from Python tuple:

tup=(1,4.5,'r','p',[3,4],(5.4,76),9.0,13)
print("tup[2:5]:",tup[2:5]) #accessing 3rd to 6th elements, 6th excluded

print("tup[-1:-4]:",tup[-4:-1]) #accessing last 4th to last second elements

print("tup[3:]:",tup[3:]) #accessing all elements from 4th one

print("tup[-2:]:",tup[-2:]) #accessing all elements from last 2nd one

print("tup[:5]:",tup[:5]) #accessing all elements till 5th one

print("tup[-2:]:",tup[:-3]) #accessing all elements before last 3rd one

print("tup[3:-2]:",tup[3:-2]) #accessing all elements from 4th element and before last 2nd element

print("tup[:]:",tup[:]) #accessing all elements

print("tup[2:2]:",tup[2:2])#printing empty tuple

Output:

tup[2:5]: (‘r’, ‘p’, [3, 4])

tup[-1:-4]: ([3, 4], (5.4, 76), 9.0)

tup[3:]: (‘p’, [3, 4], (5.4, 76), 9.0, 13)

tup[-2:]: (9.0, 13)

tup[:5]: (1, 4.5, ‘r’, ‘p’, [3, 4])

tup[-2:]: (1, 4.5, ‘r’, ‘p’, [3, 4])

tup[3:-2]: (‘p’, [3, 4], (5.4, 76))

tup[:]: (1, 4.5, ‘r’, ‘p’, [3, 4], (5.4, 76), 9.0, 13)

tup[2:2]: ()

3. Accessing multiple elements with a step in Python:

To access multiple elements, not continuous, but that occurs after a few positions we give the indexing as “i:j:k”. Where i is the starting index, j is the ending index and k is the step. The values of i, j, and k can be negative.

Example of accessing multiple elements with step from tuple:

tup=(1,4.5,'r','p',[3,4],(5.4,76),9.0,13)
print("tup[2:6:2]:",tup[2:6:2]) #accessing the alternate elements between index 2 and 6

print("tup[::-1]:",tup[::-1]) #accessing the  elements in reverse

Output:

tup[2:6:2]: (‘r’, [3, 4])

tup[::-1]: (13, 9.0, (5.4, 76), [3, 4], ‘p’, ‘r’, 4.5, 1)

4. Accessing value of the inner container in Python

We can access the elements of the inner containers of the tuple like lists, tuples, etc. To do so first we access that container using indexing. Then add another index using square brackets to access a particular value.

Example of accessing inner value of a container in Python tuple:

tup=(1,4.5,'r','p',[3,4],(5.4,76),9.0,13)

print("tup[4][1]:",tup[4][1]) #accessing second element of the list, which is at 5th position

print("tup[5][0]:",tup[5][0]) #accessing the first element of the tuple, which is at 6th position

Output:

tup[4][1]: 4

tup[5][0]: 5.4

5. Getting error on wrong indexing in Python

When we give the index as any value other than an integer, we get an error. Also, the index should be less than the length of the tuple and greater than or equal to the negative of the length of the tuple. If the index does not lie in this range, we get an error because there are no elements outside this range. For example,

Example of getting an error on wrong indexing :

tup=(1,4.5,'r','p',[3,4],(5.4,76),9.0,13)

print("tup[8]:",tup[8])

print("tup[-10]:",tup[-10])

Output:

Traceback (most recent call last):
File “<pyshell#1>”, line 1, in <module>
print(“tup[8]:”,tup[8])
IndexError: tuple index out of rangeTraceback (most recent call last):
File “<pyshell#2>”, line 1, in <module>
print(“tup[-10]:”,tup[-10])
IndexError: tuple index out of range

Immutability in Python Tuples

One of the important properties of tuples is their immutability. The elements can neither be changed, added, or deleted from the tuple. We get an error when we try doing them. The following example shows this.

Example of getting an error on trying to modify a tuple:

tup=(1,3.4, 't', "Python", [5.6,8])

tup[4]="i" #changing value

del tup[3] #deleting value

tup.append('a') #adding value

Output:

Traceback (most recent call last):
File “<pyshell#1>”, line 1, in <module>
tup[4]=”i” #changing value
TypeError: ‘tuple’ object does not support item assignmentTraceback (most recent call last):
File “<pyshell#2>”, line 1, in <module>
del tup[3] #deleting value
TypeError: ‘tuple’ object doesn’t support item deletionTraceback (most recent call last):
File “<pyshell#3>”, line 1, in <module>
tup.append(‘a’) #adding value
AttributeError: ‘tuple’ object has no attribute ‘append’

Deleting the tuple in Python

We cannot delete a particular element of the tuple, but we can delete the whole tuple. We cannot access it after deleting, we get a NameError if we try doing so. For example,

Example of deleting a Python tuple:

tup=(12,6,'a',7.8)
del tup
print(tup)

Output:

Traceback (most recent call last):
File “<pyshell#4>”, line 1, in <module>
print(tup)
NameError: name ‘tup’ is not defined

Modifying mutable items in Python tuple

Though we cannot change the tuple elements, we can modify the mutable elements like lists. For example,

Example of modifying mutable elements in a tuple:

tup=(3,'s',[4.5,6],6.7)
tup[2].append('a')
print(tup)

Output:

(3, ‘s’, [4.5, 6, ‘a’], 6.7)

The meaning of immutability applies to the id of the value of each element of the tuple. Remember, when we try to modify the value of a variable, the id of the variable changes to that of the new value. Whereas the id of that value remains the same.

Each item of a tuple has its own id if its values do not match. If they match, then the id is the same for those elements that have the same value. This is shown below.

Example of checking id of the elements in a tuple:

tup=('a',5,'a',7.6,[1,2])

print(id(tup[0])==id(tup[2])) #1st and 3rd elements have same value

print(id(tup[1])==id(tup[3])) #2n and 4th elements have different values

Output:

True

False

We cannot modify tuples, because we cannot change the ids of the elements of the tuple. But when we try to modify a mutable element like a list in a tuple, the list’s id does not change. So, we are allowed to do that. This is shown below.

Example of showing that id of the list in a tuple does not change on modifying it :

tup=(3,'s',[4.5,6],6.7)
id(tup[2])

tup[2].append('a')
print(tup)

id(tup[2])

Output:

2007208209216

(3, ‘s’, [4.5, 6, ‘a’], 6.7)

2007208209216

Python Tuple Methods

Because of its immutability, we cannot use some of the methods like:

1. append() and extend(), because we cannot add elements to the tuple
2. remove() and pop(), because we cannot delete elements of a tuple

But we can use other methods that do not modify tuples. Some of them are listed below.

1. Python index():

This function returns the location of the first occurrence of the value given as an argument. It gives an error if the element is not in the tuple.

Example of using the index() function on a Python tuple:

tup=(1,3.4,3,'t',6,3,0.9,'t',3.0)
tup.index('t')

tup.index(10)

Output:

3

Traceback (most recent call last):
File “<pyshell#2>”, line 1, in <module>
tup.index(10)
ValueError: tuple.index(x): x not in tuple

We can see that ‘t’ is present at indexes 3 and 7. But it gave the lowest index.

2. Python count():

This function returns the number of times a value occurs in a tuple. It gives if the values do not exist in the tuple

Example of using the count() function on a Python tuple:

tup.count(3)

tup.count('b')

Output:

3

0

Tuple Functions in Python

1. Python len():

The len() returns the length of the tuple, which if given as an argument to the function.

Example of using Python len() function on a tuple:

tup=(1,3.4,3,'t',6,3,0.9,'t',3.0)
len(tup)

Output:

9

2. Python max():

This function returns the maximum value of the tuple having values of the same data type. If we try to apply the max() on a tuple with different data types we will get an error because values of different data types cannot be compared.

Example of using Python max() function on a tuple:

tup=(-1,8,-6,4,19)
max(tup)

tup=(-1,'s',5,6,'t')
max(tup)

Output:

19

Traceback (most recent call last):
File “<pyshell#3>”, line 1, in <module>
max(tup)
TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’

3. Python min():

This function returns the minimum value values of the tuple, all values belonging to the same data type. If we try to apply the min() on a tuple with different data types we will get an error because values of different data types cannot be compared.

Example of using Python min() function on a tuple:

tup=(-1,8,-6,4,19)
min(tup)

tup=(-1,'s',5,6,'t')
min(tup)

Output:

-6

Traceback (most recent call last):
File “<pyshell#3>”, line 1, in <module>
min(tup)
TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’

4. Python sum():

This function returns the sum of all values of the tuple if all values belong to the same data type. If we try to apply the sum() on a tuple with different data types we will get an error because values of different data types cannot be added.

Example of using the sum() function on Python tuple:

tup=(-1,8,-6,4,19)
sum(tup)

tup=(-1,'s',5,6,'t')
sum(tup)

Output:

24

Traceback (most recent call last):
File “<pyshell#3>”, line 1, in <module>
sum(tup)
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

5. Python sorted():

This function returns the version of the tuple in the form of a list with all elements arranged in increasing order. This is the case if all values belong to the same data type.

If we try to apply the sorted() on a tuple with different data types we will get an error because values of different data types cannot be compared.This function does not affect the order of elements in the tuple, it only returns the arranged version.

Example of using the sorted() function on Python tuple:

tup=(-1,8,-6,4,19)

sorted(tup)

tup

tup=(-1,'s',5,6,'t')
sorted(tup)

Output:

[-6, -1, 4, 8, 19]

(-1, 8, -6, 4, 19)

Traceback (most recent call last):
File “<pyshell#4>”, line 1, in <module>
sorted(tup)
TypeError: ‘<‘ not supported between instances of ‘str’ and ‘int’

6. Python all():

This function checks if all the elements are not empty or 0 and returns either True or False. It returns False if any of the elements is empty or 0. It can work on any tuple.

Example of using the all() function on Python tuple:

tup=(-1,'s',5,6,'t')
all(tup)

tup=('',0,'t',2,5.6)
all(tup)

Output:

True

False

7. Python any():

This function checks if any of the elements are not empty or 0 and returns either True or False. It returns False only if all of the elements are empty or 0. It can work on any tuple.

Example of using the any() function on a tuple:

tup=(-1,'s',5,6,'t')
any(tup)

tup=('','t',3,5.6,0)
any(tup)

tup=('','',0,0,'')
any(tup)

Output:

True

True

False

8. Python tuple():

This function converts the other iterable data types into a tuple. It can work on lists, sets, and strings.

Example of using the tuple() function:

list1=[1,2,'a',(3,4),[4,5]]
tup1=tuple(list1)
print("The type of ",tup1,"is:",type(tup1))

set1={1,'a',3.4,(4,5)}
tup2=tuple(set1)
print("The type of ",tup2,"is:",type(tup2))

string="PythonGeeks"
tup3=tuple(string)
print("The type of ",tup3,"is:",type(tup3))

Output:

The type of (1, 2, ‘a’, (3, 4), [4, 5]) is: <class ‘tuple’>

The type of (1, (4, 5), 3.4, ‘a’) is: <class ‘tuple’>

The type of (‘P’, ‘y’, ‘t’,’h’, ‘o’, ‘n’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’) is: <class ‘tuple’>

Operations on Tuples in Python

We will talk about operations that we can do on tuples. These are:

1. Addition and Multiplication:

We can add two tuples using the ‘+’ operator. The elements of the second tuple will get concatenated to the elements of the first tuple.

We can do multiplication of a tuple with a positive integer ‘n’ using the ‘*’ operator. The tuple gets added to itself n times and the resulting tuple is returned. For example,

Example of addition and multiplication of tuples:

tup1=[1,2,'a',5.9]
tup2=['t',"python",7]
print("Addition:",tup1+tup2)

print("Multiplication:",tup1*3)

Output:

Addition: [1, 2, ‘a’, 5.9, ‘t’, ‘python’, 7]

Multiplication: [1, 2, ‘a’, 5.9, 1, 2, ‘a’, 5.9, 1, 2, ‘a’, 5.9]

2. Membership:

There are two membership operators, namely, ‘in’ and ‘not in’. These are used to check if a value exists in the tuple. The function ‘in’ gives True if it exists else False. The ‘not in’ does the opposite.

Example of finding membership in tuples:

tup1=[1,2,'a',5.9,5,'Python']
'a' in tup1

19 in tup1

'5' not in tup1

'Python'  not in tup1

Output:

True

False

True

False

3. Identity:

In Python, there are two identity operators and these are ‘is’ and ‘is not’. These are used to check if two tuples are located in the same part of memory or not.

Example of checking the identity of tuples:

tup1=(1,2,3)
tup2=(1,2,3)
tup1 is tup2

Output:

False

We got the output as False, though the values of the tuples are the same because their memory locations or ids are different.

4. Logical operators:

We can use logical operators like == and !=. on the tuples. The operators == and != can work on tuples with corresponding elements of different data types, but the others give an error.

These (>,<.>=,<=) check till the inequality is obtained and return the result without checking the further elements.

Example of doing logical operations on tuples:

tup1=(1,2,3,5,19)
tup2=(1,1,34,23,78)

tup1>tup2

tup3=(1,2,3)
tup4=('1','2','3')

tup3>tup4

tup4==tup3

Output:

True

Traceback (most recent call last):
File “<pyshell#6>”, line 1, in <module>
tup3>tup4
TypeError: ‘>’ not supported between instances of ‘int’ and ‘str’

False

Other features of Python Tuples

1. Iterations on tuples in Python

We can go through each element of the tuple using loops. The most common loop used for this purpose is the ‘for loop’.

Example of doing iteration on tuples:

tup=(3,5.6,'a',[1,2],(9,5),7.6)
for ele in tup:
    print(ele)

Output:

3
5.6
a
[1, 2]
(9, 5)
7.6

2. Unpacking Python Tuples

Unpacking is a way of assigning the elements of a tuple to the variables separated by commas on the right side of the equal symbol. The number of variables should be the same as the elements of the tuple, else it will get an error.

Example of doing iteration on tuples:

tup1=[1,'a',5.6]
x,y,z=tup1

print(x)

print(y)

print(z)

Output:

1

a

5.6

Python Nested Tuples

Nested tuples are the tuples with the elements as tuples. A tuple can have any number of tuples, with each having inner tuples.

We can access the values of inner lists by adding another square bracket with the index of the value. An example of creating a nested tuple and accessing data is shown below.

Example of creating nested tuples and accessing elements:

nest_tup=((1,2.9,3),(4.0,3,9),('a',('b',4),'c'))

print(nest_tup)

print(nest_tup[0])

print(nest_tup[1][0])

print(nest_tup[2][1][0])

Output:

((1, 2.9, 3), (4.0, 3, 9), (‘a’, (‘b’, 4), ‘c’))

(1, 2.9, 3)

4.0

b

Python Lists vs Tuples

One of the differences between lists and tuples we learned is the immutability of tuples. These are other differences and advantages over lists in some cases like:

1. The execution time is faster for the tuples because of their immutability

2. For the same reason, the tuples are memory efficient compared to the lists

3. Tuples help in the scenarios where we want the data to not be modified and have read-only property.

4. Tuples can be used as keys for the dictionaries as dictionary keys are immutable, but this is not possible with lists

Interview Questions on Tuples in Python

Q1. Write a function to sum all the elements of a tuple without using sum().
Ans 1. Below is the example of summing values of tuples:

tup=(1,2,3,4,5,-6,7)
sum =0
for i in tup:
  sum=sum+i

  
print(sum)

Output:

16

Q2. Write a program to print all the elements tuple at an interval 3 in reverse order.
Ans 2. Below is the example of printing all the elements tuple at an interval 3 in reverse order.

tup=(1,2,'a','t',5.7)
print(tup[::-3])

Output:

(5.7, 2)

Q3. Write a program to append a value to a tuple.
Ans 3. We can create another tuple with a single value and concatenate the tuples.

tup1=(1,2,3)
tup2=(5,)

tup1=tup1+tup2
tup1

Output:

(1, 2, 3, 5)

Q4. Write a program to access elements from nested tuples.
Ans 4. Below is the example of accessing elements from nested tuples:

tup=((1,2,3),(4,5,6,7),('a','b','c'))
tup[1][2]

Output:

6

Q5. Write a program to print the next value of the given value in the tuple.
Ans 5. We can find the index of the given value using the index() function. Then find the next value giving the index as the obtained index+1.

tup=(1,2,'a','t',5.7)
ind=tup.index('a')
print(tup[ind+1])

Output:

t

Quiz on Python Tuples

Conclusion

In this article, we learned about tuples, accessing elements of tuples, their immutability property, etc. Then we saw some functions and methods on tuples. After that, we saw some operations on them and advantages of tuples over lists. Finally, we saw some interview questions. Hope you understood the topics. Happy learning!

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google | Facebook


Leave a Reply

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