Python Tuples : In this Unit…
Python Tuples with Examples and Basic Operations on Tuples
A Python Tuple is a sequence which stores a group of elements or items.
Python Tuples are similar to Python Lists but the main difference is tuples are immutable (cannot be modified) whereas lists are mutable (can be modified).
ALSO SEE : Python Tuples Immutability Explained !!
Python Tuples are faster than lists in terms of performance (item lookup). This is because a list is stored in two blocks of memory (One is fixed sized and the other is variable sized for storing data) whereas Python tuples requires only single block of memory to store data.
Since Python Tuples are immutable, we can not modify a tuple after creation.
Common methods of Python Lists can not be applied on Python Tuples like append(), extend(), insert(), remove(), pop().
Python Tuple elements are enclosed within ‘( )‘.
Additionally, We can also use tuple() to typecast any iterable object to a list. Like below,
s = "cog" # string
n = {10} # set
l = [4, 5] # list
print(tuple(s)) # string -> tuple
print(tuple(n)) # set -> tuple
print(tuple(l)) # list -> tuple
O/P
(‘c’, ‘o’, ‘g’)
(10,)
(4, 5)
Tuples in Python can have duplicate values.
Creating a Python Tuple
Tuples can be created by writing elements within parentheses (). Just like Lists, Tuples can also have elements of different types.
t = () # empty tuple
t = (1, ) # tuple with one element, observe ' , ' at the end
t = (1, 2, 3) # tuple with three element
Please note that t = (10) will be treated as an integer value, whereas t = (10, ) is a tuple.
Additionally, If we do not mention any brackets and write the elements separating them by commas, then, they are considered as tuple, by def.
t = 1, 2, 3
print(type(t)) prints '<class 'tuple'>'
Length of a Python Tuple
Length of a Python Tuple signifies the number of elements in that particular tuple. We can use the len() function to find the length of a tuple.
t = (3, "hello", "nice", 4)
print(len(t)) # prints 4
Indexing in Python Tuples
For tup = (10, “hello”, 30, 50)

Indexing in Python Tuples is same as in Python Lists, starting with 0 to len(tup)-1.
Python Tuples also supports negative indexing, starting from -1 to len(tup). So,
tup[0] will give us 10,
tup[1] will give us “hello”,
Similarly, tup[-2] will give us 30.
Traversing a Python Tuple
Traversal, in simpler words, means to visit each element of the given tuple one by one.

In Python Tuples, traversal can be done in two ways :
1. for loop
2. while loop
Traversing Tuple using for loop
Program : To traverse a given tuple using for loop.
planets = ('mercury', 'venus', 'earth', 'mars')
for each_planet in planets:
print(each_planet, end=' ')
O/P :
mercury venus earth mars
Here, variable ‘each_planet’ is acting as a tuple element (iterator).
We can also iterate over a given sequence using range() function within the for loop.
range() function in Python is used to generate a sequence or series of numbers, starting from 0, ending just before the given limit and increments by 1. These are the default values which can be changed as per the requirements.
Syntax
range(start, end+1, step_size)
start : This signifies the starting point of the sequence.
end : This signifies the ending point of the sequence.
step_size : This signifies the value with which each digit of sequence will either increase or decrease.
Like, in series 2, 4, 6, 8, we have two as a step size.
Below are the different ways in which range() function can be used :
1. range(n) : We will use this when we want to generate a sequence of numbers from 0 to n-1, keeping 1 as step size.
2. range(0, 10) : We will use this when we want to generate a sequence of numbers from 0 to 9, keeping 1 as step size.
3. range(0, 10, 2) : We will use this when we want to generate a sequence of numbers from 0 to 9, keeping 2 as step size. This series will be as ‘0, 2, 4, 6, 8’.
4. range(10, 0, -1) : We will use this when we want to generate a sequence of numbers from 10 to 1,
Program : To traverse a given tuple using for loop (range).
planets = ('mercury', 'venus', 'earth', 'mars')
for i in range(0, len(planets)):
print(planets[i], end=' ')
print()
# reverse order
for i in range(len(planets)-1, -1, -1):
print(planets[i], end=' ')
print()
# reverse using negative indexing
for i in range(-1, -(len(planets))-1, -1): # loop will run for index -1 to -4
print(planets[i], end=' ')
O/P :
mercury venus earth mars
mars earth venus mercury
mars earth venus mercury
We all know that just like lists, Python Tuples are indexable too. In the above program, we were able to access each element of the given tuple with its index using range() function.
Consider line-3 of code
for i in range(0, len(planets)):
This for loop will run ‘len(planets)’ times, starting from i = 0 and ending at i = len(planets) – 1.
Variable ‘i‘ holds integer value.
Here, in our program, len(planets) = 4
Hence, this for loop will run four times, starting from 0 and ending to 3.

Traversing tuple using while loop
Program : To traverse a given tuple using while loop.
planets = ('mercury', 'venus', 'earth', 'mars')
i = 0
while i < len(planets):
print(planets[i], end= ' ')
i+=1
print()
# reverse order
j = len(planets)-1
while j >= 0:
print(planets[j], end= ' ')
j-=1
O/P :
mercury venus earth mars
mars earth venus mercury
Slicing in Python Tuples
Slicing refers to the process of extracting a piece or part of the tuple following 0-based indexing. Slicing is typically done in the following format
tuple[start: stop: stepsize]
Here, ‘start’ represents the position of starting element of the tuple, ‘stop’ represents the position of ending element of the tuple and ‘stepsize’ indicates the increment/ decrement.
For a tuple of ‘n‘ elements, default value for ‘start’ will be 0, ‘end’ will be (n-1), ‘stepsize’ will be 1.
Let’s see different slicing ways for ‘+’ stepsize
tuple = (1, 2, 3, 4, 5)
print(tuple[:]) # prints all elements of tuple i.e 1, 2, 3, 4, 5
print(tuple[1:4]) # prints all elements from position 1 to position 3 (4-1) i.e 2, 3, 4
print(tuple[::2]) # here, start = 0, end = 4 (5-1), prints elements from position 0 to position 4, keeping stepsize as 2, i.e 1, 3, 5
print(tuple[1::]) # here, start = 1, end = 4, prints elements from position 1 to position 4 i.e 2, 3, 4, 5
For ‘-‘ stepsize
If the stepsize is negative then elements are extracted in reverse order (following 1-based indexing), rest everything remains same.
tuple = (1, 2, 3, 4, 5)
print(tuple[::-2]) # prints 5, 3, 1 as stepsize is 2 and '-' sign indicates reverse order
When the stepsize is positive, then elements are extracted from left to right, whereas in case of negative stepsize, elements are extracted from right to left.
tuple = (1, 2, 3, 4, 5)
print(tuple[-4:-1]) # prints 2, 3, 4
In the above code, start is ‘-4’ which is the fourth element from right, elements are extracted from position ‘start’ to ‘end – 1’, hence, from -4 to -2.
Find the O/P for t = (3, 4, 6, 12, 5, 10)
print(t[2:5])
Ans. (6, 12, 5)
print(t[3::2])
Ans. (12, 10)
print(t[4:5:1])
Ans. (5,)
print(t[2:4:-1])
Ans. ()
print(t[-2:-4:-1])
Ans. (5, 12)
print(t[::-4])
Ans. (10, 4)
Taking tuple as an Input
We can use input() method to take input from the user, which can be later type-casted to tuple.
s = tuple(input('Enter your tuple : '))
print("tuple is : ",s)
O/P
Enter your tuple : 3412
tuple is : (‘3’, ‘4’, ‘1’, ‘2’)
We can also use eval() function to evaluate whether typed elements are a list or a tuple.
s = eval(input('Enter your tuple : '))
print("tuple is : ",s)
Concatenation of Python Tuples
Concatenation refers to the process of attaching two or more tuples to form a resultant tuple.
We can simple use ‘+’ operator to perform tuple concatenation.
inner_planets = ('mercury', 'venus', 'earth', 'mars') # tuple1
outer_planets = ('jupiter', 'saturn', 'uranus', 'neptune') # tuple2
planets = inner_planets + outer_planets # concatenating two tuples
print("All Planets : ", planets)
O/P
All Planets : (‘mercury’, ‘venus’, ‘earth’, ‘mars’, ‘jupiter’, ‘saturn’, ‘uranus’, ‘neptune’)
Repetition of Tuples
Repetition refers to the process of repeating the elements of a tuple ‘n’ number of times.
We can simple use ‘*’ operator to perform tuple repetition.
If we write, t*n, then it means tuple l will be repeated n number of times.
t = (2, 4, 6)
print(t * 3)
O/P
(2, 4, 6, 2, 4, 6, 2, 4, 6)
Here, tuple l, is repeated thrice as specified.
Membership in Python Tuples
Suppose if we want to check whether a given element (or a subtuple) is a member of the given tuple.
This can be done using in and not in operator in Python.
If the element is the member of the tuple, then, in operator returns True, else False.
If the element is not the member of the tuple, then, not in operator returns True, else False.
t = (1, 2, 3, 4, 5)
item = 10
print(item in t) # checking for 10 in given tuple, returns False
print(item not in t) # returns True
O/P
False
True
