Python Tuple

Tuple in Python A Tuple is a collection of immutable Python objects separated by commas. Tuples are just like lists, but we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed. The main difference being that tuple manipulation are faster than list because tuples are immutable. Since they're immutable, they can be used as keys for a dictionary. Also, Tuples are used whenever you want to return multiple results from a function.

Creating a Tuple

A tuple is defined using parenthesis. An empty tuple can be formed by an empty pair of parentheses.

example
a_tuple = () #empty tuple print(a_tuple)
output
()

Creating Tuple with values

example
a_tuple = ('East','West','North','South') print(a_tuple)
output
('East', 'West', 'North', 'South')

Python Tuple with mixed datatypes

example
a_tuple = (1,2,'sunday','monday',3.14) print(a_tuple)
output
(1, 2, 'sunday', 'monday', 3.14)
example
a_tuple = ('1899-10-34', ['Drama', 'Tale of Two Cities']) print(a_tuple)
output
('1899-10-34', ['Drama', 'Tale of Two Cities'])

Accessing tuple values

To access individual elements, we use [] square brackets where the index starts from 0.

example
a_tuple = (1,2,'sunday','monday',3.14) print(a_tuple[0]) # print 1st element print(a_tuple[1]) # print 2nd element print(a_tuple[-1]) # print last element print(a_tuple[-2]) # print 2nd last element
output
1 2 3.14 monday

Adding Tuple

example
a_tuple = ('1899-10-34', ['Drama', 'Tale of Two Cities']) print(a_tuple) print(a_tuple[0]) # print 1st element print(a_tuple[1]) # print 2nd element
output
('1899-10-34', ['Drama', 'Tale of Two Cities']) 1899-10-34 ['Drama', 'Tale of Two Cities']

Loops and Tuple

example
a_tuple = ('East','West','North','South') for dir in a_tuple: print (dir)
output
East West North South

Tuple print with index number

example
a_tuple = ('East','West','North','South') for i,dir in enumerate(a_tuple): print (i, " " , dir)
output
0 East 1 West 2 North 3 South

Concatenation of Tuples

You can add two or more Tuples by using the concatenation operator "+".

example
a_tuple = ('East','West','North','South') b_tuple = (1,2,3,4,5) c_tuple = a_tuple + b_tuple print(c_tuple)
output
('East', 'West', 'North', 'South', 1, 2, 3, 4, 5)

Tuple length

The function len returns the length of a Tuple, which is equal to the number of its elements.

example
a_tuple = ('East','West','North','South') i = len(a_tuple) print(i)
output
4

Slicing Python Tuples

Python slice extracts elements, based on a start and stop.

example
a_tuple = ('East','West','North','South') slc = a_tuple[1:3] print(slc)
output
('West', 'North')

str[1:3] - The 1 means to start at second element in the Tuples (note that the slicing index starts at 0). The 3 means to end at the fourth element in the list, but not include it. The colon in the middle is how Python's Tuples recognize that we want to use slicing to get objects in the list.

example
a_tuple = ('East','West','North','South') slc = a_tuple[:2] # slice first two elements print(slc)
output
('East', 'West')
example
a_tuple = ('East','West','North','South') slc = a_tuple[2:] # slice from 3rd element, Python starts its index at 0 rather than 1. print(slc)
output
('North', 'South')

Delete Tuple Elements

How to Tuple in Python

Tuples in Python are immutable. This means that once you have created a tuple, you can't change the elements contained within it. To explicitly remove an entire tuple, just use the del statement.

example
a_tuple = ('East','West','North','South') del a_tuple print(a_tuple)
output
Traceback (most recent call last): File "sample.py", line 8, in < module > print(a_tuple) NameError: name 'a_tuple' is not defined

Updating a Tuple

Since tuples are immutable, it cannot be changed once it has been assigned. But, if the element is itself a mutable datatype like list, its nested items can be changed.

example
a_tuple = (1,2,3,4,[5,6]) a_tuple[4][1]=12 print(a_tuple)
output
(1, 2, 3, 4, [5, 12])

Tuples as return multiple values

Functions are always only return a single value, but by making that value a tuple, we can effectively group together as many values as we like, and return them together.

example
def multi(): a=100 b=200 return (a,b) x,y = multi() print(x) print(y)
output
100 200

Nesting of Tuples

example
a_tuple = (1,2,3,4,5) b_tuple = ('a','b','c','d','3') c_tuple = (a_tuple,b_tuple) print(c_tuple)
output
((1, 2, 3, 4, 5), ('a', 'b', 'c', 'd', '3'))

Converting list to a Tuple

You can convert a List to a Tuple by using tuple()

example
a_list = [1,2,3,4,5] a_tuple = tuple(a_list) print(a_tuple)
output
(1, 2, 3, 4, 5)

Repetition in Tuples

Using the * operator repeats a list a given number of times.

example
a_tuple = ('halo','world') a_tuple = a_tuple * 2 print(a_tuple)
output
('halo', 'world', 'halo', 'world')

Tuple repetition Count

Tuple.count(x) return the number of times x appears in the Tuple.

example
a_tuple = ('h','e','l','l','o') cnt=a_tuple.count('l') print(cnt)
output
2

zip() function

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

example
a_tuple = (1,2,3,4,5) b_tuple = ('a','b','c','d','e') for num, alp in zip(a_tuple,b_tuple): print(num, alp)
output
1 a 2 b 3 c 4 d 5 e

Tuple min(), max()

The min() returns the minimum value from a tuple and max() returns the maximum value from the tuple.

example
a_tuple = (1,2,3,4,5) print(min(a_tuple)) print(max(a_tuple))
output
1 5

Tuple Packing and Unpacking

Process of creating collection by comma separating items within parentheses ( ) is known as packing of tuple while assigning individual items from a tuple to individual variables using assignment operator is known as unpacking of tuples.
Python Tuple Packing and Unpacking