0% found this document useful (0 votes)
2 views9 pages

Tuples in Python (1)

The document provides a comprehensive overview of tuples in Python, including their definition, creation methods, and characteristics such as immutability. It covers various operations that can be performed on tuples, including concatenation, replication, membership testing, and slicing. Additionally, the document discusses tuple methods and functions like len(), index(), count(), max(), min(), sorted(), and sum().
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views9 pages

Tuples in Python (1)

The document provides a comprehensive overview of tuples in Python, including their definition, creation methods, and characteristics such as immutability. It covers various operations that can be performed on tuples, including concatenation, replication, membership testing, and slicing. Additionally, the document discusses tuple methods and functions like len(), index(), count(), max(), min(), sorted(), and sum().
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TUPLES IN PYTHON

Definition and Introduction:

1. A Tuple is Python sequence that can store elements/values of any data type. A Tuple can store any number
of integers, floats, strings or even a List or Tuple.
2. The elements of the Tuple are declared with first bracket ( ) separated by comma.
3. A Tuple is an immutable object in Python i.e. the elements of the tuple cannot be modified in place.
4. A Tuple can be declared by the following syntax:
Tuplename=(element1,element2,………)
For e.g. –
A Tuple of integers- T=(10,20,30,40,50)
A Tuple of elements of mixed data type: P=(12,’A’,56.67,23,’INDIA’,True)

Creating Tuples:

Tuples can be created in many ways:

a) Creating an empty Tuple:


Process 1:
>>> T=()
>>> T
()
Process 2:
>>> T2=tuple()
>>> T2
()
b) Creating a tuple from an existing sequence:
>>> S='COMPUTER'
>>> T=tuple(S)
>>> T
('C', 'O', 'M', 'P', 'U', 'T', 'E', 'R')
c) Creating a Tuple with a single element:
To create a tuple with a single element just add a comma after the single element as follows:
>>> T=(200,)
>>> T
(200,)
>>> type(T)
<class 'tuple'>
d) Creating a tuple from another tuple:
>>> T1=(10,20,30)
>>> T2=tuple(T1)
>>> T2
(10, 20, 30)
e) Taking inputs in a tuple at runtime:

i) The eval() is used to create a set of integers in a tuple and to be entered through first
brackets. e.g.
>>> T=eval(input('Enter elements in a tuple:'))
Enter elements in a tuple:(10,5,78,55,33,24)
>>> T
(10, 5, 78, 55, 33, 24)
>>> type(T)
<class 'tuple'>
ii) A single digit or a single character can be given as a tuple input at a time.
e.g.
>>> T=tuple()
>>> T=tuple(input('Enter element:'))
Enter element:12AP90
>>> T
('1', '2', 'A', 'P', '9', '0')

iii) Taking inputs in a tuple using loop:


e.g.
Python Code to store name of ‘n’ number of countries in a tuple.

T=tuple()
n=int(input('Enter the number of countries:'))
for i in range(1,n+1):
c=input('Enter Country Name:')
T=T+(c,)

print('The Country Names are:',T)

Output:
Enter the number of countries:5
Enter Country Name:Japan
Enter Country Name:India
Enter Country Name:USA
Enter Country Name:Belgium
Enter Country Name:Romania
The Country Names are: ('Japan', 'India', 'USA', 'Belgium', 'Romania')

Nested Tuple:

A Nested Tuple is a tuple within a tuple. A Nested Tuple can be created as per the following:
T1=tuple()
T1=eval(input('Enter elements in a tuple:'))
T2=tuple()
T2=tuple(input('Enter elements in a tuple:'))
T=(20,T2,'A',T1)
print('Main Tuple=',T)

e.g.
Enter elements in a tuple:(10,'Paper',20)
Enter elements in a tuple:(3.5,90,'Eraser')
Main Tuple= (20, "(3.5,90,'Eraser')", 'A', "(10,'Paper',20)")

Accessing Tuple Elements:


The elements of a tuple can be accessed by mentioning its index within square brackets. Python tuple
supports forward as well as backward indexing. Forward indexing starts from 0 and ends at TupleLength-
1. Backward indexing starts from -1 and ends at (-TupleLength)
e.g. T=(10,20,30,40,50,60)

Backward Indexing
-6 -5 -4 -3 -2 -1

10 20 30 40 50 60

0 1 2 3 4 5
Forward Indexing e.g.

>>> L=(10,20,30,40,50,60)
>>> L[4]
50
>>> L[-3]
40
>>> L[0]
10
>>> L[-1]
60
>>> L[-2]*L[0]
500
>>> L[-12]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
L[-12]
IndexError: Tuple index out of range

For any element Forward Index-Backward Index=Length of the Tuple.

Traversing a Tuple:

Accessing the elements of a tuple can be done using for loop i.e. for loop can be used to traverse a tuple.
Syntax:
for <variablename> in tuple:
#process the elements

e.g.
T=(25,27,12,55,14) for x in T:
print(x,end=' ')

Output:
25 27 12 55 14

Tuple as immutable sequence:

A Tuple is an immutable sequence i.e. the contents of the tuple cannot be edited.
>>> T=('A',34,88,'B')
>>> T[2]=100
Traceback (most recent call last):
File "<pyshell#44>", line 1, in <module>
T[2]=100
TypeError: 'tuple' object does not support item assignment.
TUPLES IN PYTHON

The different operations to be performed with tuples are:


i) Concatenation
ii) Replication
iii) Traversing
iv) Membership Testing
v) Comparison
vi) Tuple Slicing
vii) Unpacking Tuples
viii) Deleting Tuples

i) Concatenation:
The concatenation operator ‘+’ is used to join two tuples. In case of joining, the elements
of the 2nd tuple is added to the elements of the 1st tuple.
e.g1.
>>> T1=(12,'A',78)
>>> T2=(9,67.5,'K','P')
>>> T3=T1+T2
>>> T3
(12, 'A', 78, 9, 67.5, 'K', 'P')
e.g.2
>>> T1=(10,20)
>>> T2=T1+(30,)
>>> T2
(10, 20, 30)
>>> T3=T2+(40)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
T3=T2+(40)
TypeError: can only concatenate tuple (not "int") to tuple

ii) Replication/Repetition:

The replication operator ‘*’ is used to replicate or repeat a tuple –a definite number of
times.
e.g.
>>> T=(100,'A',3)
>>> T*3
(100, 'A', 3, 100, 'A', 3, 100, 'A', 3)

iii) Traversing:

The for loop can be used to traverse a tuple i.e. process each element of the tuple.
e.g.1
T=(10,20,30,40)
for x in T:
print(x+20)

Output:
30
40
50
60

e.g.2
T1=(10,20,30,40)
T2=()
for x in T1:
T2=T2+(x*3,)
print(T2)

Output:
(30, 60, 90, 120)

iv) Membership Testing:


The membership operator ‘in’ or ‘not in’ return True or False depending on whether an
element is present in the tuple or not.
e.g.
>>> L=(12,'B',78,'R',8,20,'C')
>>> 'C' in L
True
>>> 'K' not in L
True
>>> 25 in L
False

v) Comparison:

Two tuples can be compared using relational/comparison operator. The comparison can be
done by comparing the tuples element by element.
>>> (10,40,50,35)>(8,89,5,12,78)
True
>>> (20,85,88)<=(-7,39,22)
False

vi) Tuple Slicing:


A tuple can be sliced-i.e. slice of the tuple can be extracted based on the following syntax:
print(T[startindex:stopindex:stepvalue])
Here:
startindex is included, stopindex is excluded, stepvalue is optional (Default value is 1)

e.g.
s=(25,'A',28,'E',18,'F',16)
print(s[0:4]) # (25, 'A', 28, 'E')
print(s[3:6]) # ('E', 18, 'F')
print(s[1:]) # ('A', 28, 'E', 18, 'F', 16)
print(s[1::2]) # ('A', 'E', 'F')
print(s[3:20:3]) # ('E', 16)
print(s[-1:-8:-1]) # (16, 'F', 18, 'E', 28, 'A', 25)
print(s[-2:-6]) # ()
print(s[-2:-6:-2]) # ('F', 'E')
vii) Unpacking Tuples:

Creating a tuple from a set of values is called Packing and creating individual values from
a tuple’s elements is called Unpacking. Although tuple is immutable but still we can modify
the elements of a tuple by unpacking and packing technique.
e.g.
T=(10,20,50,40)
A,B,C,D=T
T=(A+1,B+2,C+3,D+3)
print(T)
Output:
(11, 22, 53, 43)

viii) Deleting Tuple:

Since Tuple is immutable- its individual element cannot be deleted. However, you can delete
the entire tuple by the del statement.
e.g.
>>> T=(100,200,300,400)
>>> del T
>>> T
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
T
NameError: name 'T' is not defined
TUPLES IN PYTHON

Tuple supports different library functions/methods. These methods can be executed using the syntax:
[Link] ()
The functions/methods are:

i) len():
This function returns the total number of elements in a tuple.
>>> L=(45,78,23,55,'A',10,'G')
>>> len(L)
7

ii) index():
This function returns the index position of the first matched item from the tuple. If the element
is not found , then python raises an error message.
e.g.
e.g.
>>> L=(10,20,30,40,40,50,30,90)
>>> [Link](20)
1
>>> [Link](40)
3

iii) count():
This function returns the number of times a particular element present in the tuple.
e.g.
>>> L=(20,40,40,60,50,40,70,40,90)
>>> [Link](40)
4
>>> [Link](20)
1
>>> [Link](100)
0

iv) max():
This function returns the maximum element in a tuple.
>>> L=(37,0,9)
>>> max(L)
37

v) min():
This function returns the minimum element in a tuple.
>>> L=(38,-9,0)
>>> min(L)
-9

vi) sorted():
This function returns a list by sorting the elements of a tuple.
>>> T=(27,6,29,98,36)
>>> sorted(T)
[6, 27, 29, 36, 98]
>>> T
(27, 6, 29, 98, 36)

vii) sum():
This function returns the sum of the elements of a tuple provided the tuple is containing all
integer elements.
e.g.
>>> T=(36,16,77,15,83,21)
>>> sum(T)
248

You might also like