SlideShare a Scribd company logo
2
Most read
5
Most read
6
Most read
TUPLES
Tuple Introduction
A tuple is an ordered sequence of elements of different data types, such as
integer, float, string, list or even a tuple.
 Elements of a tuple are enclosed in parenthesis (round brackets) and are
separated by commas.
Like list and string, elements of a tuple can be accessed using index values,
starting from 0.
>>> tuple = () # Empty Tuple
>>> Tuple = (1) # Tuple with single element
>>> tuple1 = (1,2,3,4,5) # tuple of integers
>>> tuple2 =('Economics',87,'Accountancy',89.6) # tuple of mixed data types
NOTE:
If we assign the value without comma it is treated as integer.
It should be noted that a sequence without parenthesis is treated as tuple by
default.
Creation of Tuple
tuple() function is used to create a tuple from other sequences.
Tuple Creation from List :
Tuple creation from String :
Tuple creation from input()
Tuple creation using eval() :
for Ex: Tuple = eval(input(“Enter elements”))
Elements of a tuple can be accessed in the same way as a list or string using
indexing and slicing.
>>> tuple1 = (2,4,6,8,10,12) # returns the first element of tuple1
>>> tuple1[0] # returns fourth element of tuple1
2
>>> tuple1[3]
8
>>> tuple1[15] # returns error as index is out of range
IndexError: tuple index out of range index
>>> tuple1[1+4] # an expression resulting in an integer
12
>>> tuple1[-1] # returns first element from right
12
NOTE:
Tuple is an immutable data type. It means that the elements of a tuple cannot
be changed
Accessing Elements in a Tuple
Concatenation It allows to join tuples using concatenation operator depicted
by symbol +. We can also create a new tuple which contains the result of this
concatenation operation.
>>> tuple1 = (1,3,5,7,9)
>>> tuple2 = (2,4,6,8,10)
>>> tuple1 + tuple2 # concatenates two tuples (1, 3, 5, 7, 9, 2, 4, 6, 8, 10)
Concatenation operator (+) can also be used for extending an existing tuple.
When we extend a tuple using concatenation a new tuple is created.
>>> tuple3(1, 2, 3, 4, 5, 6) # more than one elements are appended
>>> tuple4 = tuple3 + (7,8,9)
>>> tuple4
(1, 2, 3, 4, 5, 6, 7, 8, 9)
Repetition It is denoted by the symbol *(asterisk).
It is used to repeat elements of a tuple. We can repeat the tuple elements.
The repetition operator requires the first operand to be a tuple and the second
operand to be an integer only.
>>> tuple1 = ('Hello','World')
>>> tuple1 * 2 #tuple with single element
('Hello', 'World', 'Hello', 'World’)
Tuple Operations
Membership
The in operator checks if the element is present in the tuple and returns True,
else it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' in tuple1
True
The not in operator returns True if the element is not present in the tuple, else
it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' not in tuple1
False
Slicing
Like string and list, slicing can be applied to tuples also.
>>> tuple1 = (10,20,30,40,50,60,70,80) # tuple1 is a tuple
>>> tuple1[2:7] (30, 40, 50, 60, 70) # elements from index 2 to index 6
>>> tuple1[0:len(tuple1)] # all elements of tuple are printed
(10, 20, 30, 40, 50, 60, 70, 80)
>>> tuple1[:5] (10, 20, 30, 40, 50) # slice starts from zero index
>>> tuple1[2:] (30, 40, 50, 60, 70, 80) # slice is till end of the tuple
Tuple Deletion
Tuple unpacking
Error shown because
deletion of a single
element is also
possible.
Complete tuple has been
deleted. Now error
shown on printing of
tuple.
Method Description Example
len() Returns the length or the number of
elements of the tuple passed as the
argument
>>> tuple1 = (10,20,30,40,50)
>>> len(tuple1)
5
tuple() Creates an empty tuple if no argument
is passed
Creates a tuple if a sequence is passed
as argument
>>> tuple1 = tuple()
>>> tuple1 ( )
>>> tuple1 = tuple('aeiou') #string
>>> tuple1 ('a', 'e', 'i', 'o', 'u')
>>> tuple2 = tuple([1,2,3]) #list
>>> tuple2 (1, 2, 3)
>>> tuple3 = tuple(range(5))
>>> tuple3 (0, 1, 2, 3, 4)
count() Returns the number of times the given
element appears in the tuple
>>> tuple1 = (10,20,30,10,40,10,50)
>>> tuple1.count(10)
3
>>> tuple1.count(90)
0
Tuple Methods and Built-in Functions
Method Description Example
index() Returns the index of the first occurrence of the
element in the given tuple
>>> tuple1 = (10,20,30,40,50)
>>> tuple1.index(30)
2
>>> tuple1.index(90)
ValueError: tuple.index(x): x not in
tuple
sorted() Takes elements in the tuple and returns a new
sorted list. It should be noted that, sorted()
does not make any change to the original tuple
>>> tuple1 =
("Rama","Heena","Raj",
"Mohsin","Aditya")
>>> sorted(tuple1)
['Aditya', 'Heena', 'Mohsin', 'Raj',
'Rama']
min()
max()
sum()
Returns minimum or smallest element of the
tuple
Returns maximum or largest element of the
tuple
Returns sum of the elements of the tuple
>>> tuple1 = (19,12,56,18,9,87,34)
>>> min(tuple1)
9
>>> max(tuple1)
87
>>> sum(tuple1)
235
A tuple inside another tuple is called a nested tuple.
In the given program, roll number, name and marks (in percentage) of
students are saved in a tuple.
To store details of many such students we can create a nested tuple
#Create a nested tuple to store roll number, name and marks of students
To store records of students in tuple and print them
st=((101,"Aman",98),(102,"Geet",95),(103,"Sahil",87),(104,"Pawan",79))
print("S_No"," Roll_No"," Name"," Marks")
for i in range(0,len(st)):
print((i+1),'t',st[i][0],'t',st[i][1],'t',st[i][2])
Output: S_No Roll_No Name Marks
1 101 Aman 98
2 102 Geet 95
3 103 Sahil 87
4 104 Pawan 79
Nested Tuples
Write a program to swap two numbers without using a temporary variable.
#Program to swap two numbers
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
print("nNumbers before swapping:")
print("First Number:",num1)
print("Second Number:",num2)
(num1,num2) = (num2,num1)
print("nNumbers after swapping:")
print("First Number:",num1)
print("Second Number:",num2)
Output:
Enter the first number: 5
Enter the second number: 10
Numbers before swapping:
First Number: 5
Second Number: 10
Numbers after swapping:
First Number: 10
Second Number: 5
Write a program to compute the area and circumference of a circle using a
function.
def circle(r): # Function to compute area and circumference of the circle
area = 3.14*r*r
circumference = 2*3.14*r # returns a tuple having two elements area and
circumference
return (area, circumference) # end of function
radius = int(input('Enter radius of circle: '))
area, circumference = circle(radius)
print('Area of circle is:', area)
print('Circumference of circle is : ', circumference)
Output:
Enter radius of circle: 5
Area of circle is: 78.5
Circumference of circle is: 31.400000000000002
Print the maximum and minimum number from this tuple.
numbers = tuple() #create an empty tuple 'numbers'
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input()) # it will assign numbers entered by user to tuple
'numbers’
numbers = numbers +(num,)
print('nThe numbers in the tuple are:')
print(numbers)
print("nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))
Output:
How many numbers do you want to enter? : 5
9 8 10 12 15
The numbers in the tuple are: (9, 8, 10, 12, 15)
The maximum number is : 15
The minimum number is : 8
Ad

Recommended

Tuple in python
Tuple in python
Sharath Ankrajegowda
 
Sets in python
Sets in python
baabtra.com - No. 1 supplier of quality freshers
 
Python tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
channa basava
 
Python programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
List in Python
List in Python
Sharath Ankrajegowda
 
Python strings presentation
Python strings presentation
VedaGayathri1
 
Python Collections
Python Collections
sachingarg0
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Python set
Python set
Mohammed Sikander
 
Introduction to Python
Introduction to Python
Mohammed Sikander
 
Python tuple
Python tuple
Mohammed Sikander
 
Python-03| Data types
Python-03| Data types
Mohd Sajjad
 
Strings in Python
Strings in Python
nitamhaske
 
Unit 4 python -list methods
Unit 4 python -list methods
narmadhakin
 
Python exception handling
Python exception handling
Mohammed Sikander
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Python Modules
Python Modules
Nitin Reddy Katkam
 
Set methods in python
Set methods in python
deepalishinkar1
 
C++ Function
C++ Function
Hajar
 
Chapter 17 Tuples
Chapter 17 Tuples
Praveen M Jigajinni
 
File handling in Python
File handling in Python
Megha V
 
Regular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Functions in Python
Functions in Python
Kamal Acharya
 
Arrays in java
Arrays in java
bhavesh prakash
 
Values and Data types in python
Values and Data types in python
Jothi Thilaga P
 
Python dictionary
Python dictionary
Sagar Kumar
 
Python strings
Python strings
Mohammed Sikander
 
Tuple in python
Tuple in python
vikram mahendra
 
Tuples class 11 notes- important notes for tuple lesson
Tuples class 11 notes- important notes for tuple lesson
nikkitas041409
 

More Related Content

What's hot (20)

Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Python set
Python set
Mohammed Sikander
 
Introduction to Python
Introduction to Python
Mohammed Sikander
 
Python tuple
Python tuple
Mohammed Sikander
 
Python-03| Data types
Python-03| Data types
Mohd Sajjad
 
Strings in Python
Strings in Python
nitamhaske
 
Unit 4 python -list methods
Unit 4 python -list methods
narmadhakin
 
Python exception handling
Python exception handling
Mohammed Sikander
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Python Modules
Python Modules
Nitin Reddy Katkam
 
Set methods in python
Set methods in python
deepalishinkar1
 
C++ Function
C++ Function
Hajar
 
Chapter 17 Tuples
Chapter 17 Tuples
Praveen M Jigajinni
 
File handling in Python
File handling in Python
Megha V
 
Regular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Functions in Python
Functions in Python
Kamal Acharya
 
Arrays in java
Arrays in java
bhavesh prakash
 
Values and Data types in python
Values and Data types in python
Jothi Thilaga P
 
Python dictionary
Python dictionary
Sagar Kumar
 
Python strings
Python strings
Mohammed Sikander
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Python-03| Data types
Python-03| Data types
Mohd Sajjad
 
Strings in Python
Strings in Python
nitamhaske
 
Unit 4 python -list methods
Unit 4 python -list methods
narmadhakin
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
C++ Function
C++ Function
Hajar
 
File handling in Python
File handling in Python
Megha V
 
Regular expressions in Python
Regular expressions in Python
Sujith Kumar
 
Values and Data types in python
Values and Data types in python
Jothi Thilaga P
 
Python dictionary
Python dictionary
Sagar Kumar
 

Similar to Tuples in Python (20)

Tuple in python
Tuple in python
vikram mahendra
 
Tuples class 11 notes- important notes for tuple lesson
Tuples class 11 notes- important notes for tuple lesson
nikkitas041409
 
PRESENTATION ON TUPLES.pptx
PRESENTATION ON TUPLES.pptx
rohan899711
 
Python-Tuples
Python-Tuples
Krishna Nanda
 
Pytho_tuples
Pytho_tuples
BMS Institute of Technology and Management
 
Python programming UNIT III-Part-2.0.pptx
Python programming UNIT III-Part-2.0.pptx
Ponnusamy S Pichaimuthu
 
Tuple in Python class documnet pritened.
Tuple in Python class documnet pritened.
SravaniSravani53
 
Python Is Very most Important for Your Life Time.
Python Is Very most Important for Your Life Time.
SravaniSravani53
 
Unit-4 Basic Concepts of Tuple in Python .pptx
Unit-4 Basic Concepts of Tuple in Python .pptx
SwapnaliGawali5
 
014 TUPLES.pdf
014 TUPLES.pdf
amman23
 
updated_tuple_in_python.pdf
updated_tuple_in_python.pdf
Koteswari Kasireddy
 
tuple in python is an impotant topic.pptx
tuple in python is an impotant topic.pptx
urvashipundir04
 
Python Tuples
Python Tuples
Soba Arjun
 
List.ppt
List.ppt
VIBITHAS3
 
Tuples in Python Object Oriented Programming.pptx
Tuples in Python Object Oriented Programming.pptx
MuhammadZuhairArfeen
 
TUPLE.ppt
TUPLE.ppt
UnknownPerson930271
 
58. Tuples python ppt that will help you understand concept of tuples
58. Tuples python ppt that will help you understand concept of tuples
SyedFahad39584
 
Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
AyushTripathi998357
 
Python Tuple.pdf
Python Tuple.pdf
T PRIYA
 
Lists_tuples.pptx
Lists_tuples.pptx
M Vishnuvardhan Reddy
 
Tuples class 11 notes- important notes for tuple lesson
Tuples class 11 notes- important notes for tuple lesson
nikkitas041409
 
PRESENTATION ON TUPLES.pptx
PRESENTATION ON TUPLES.pptx
rohan899711
 
Python programming UNIT III-Part-2.0.pptx
Python programming UNIT III-Part-2.0.pptx
Ponnusamy S Pichaimuthu
 
Tuple in Python class documnet pritened.
Tuple in Python class documnet pritened.
SravaniSravani53
 
Python Is Very most Important for Your Life Time.
Python Is Very most Important for Your Life Time.
SravaniSravani53
 
Unit-4 Basic Concepts of Tuple in Python .pptx
Unit-4 Basic Concepts of Tuple in Python .pptx
SwapnaliGawali5
 
014 TUPLES.pdf
014 TUPLES.pdf
amman23
 
tuple in python is an impotant topic.pptx
tuple in python is an impotant topic.pptx
urvashipundir04
 
Tuples in Python Object Oriented Programming.pptx
Tuples in Python Object Oriented Programming.pptx
MuhammadZuhairArfeen
 
58. Tuples python ppt that will help you understand concept of tuples
58. Tuples python ppt that will help you understand concept of tuples
SyedFahad39584
 
Python Tuple.pdf
Python Tuple.pdf
T PRIYA
 
Ad

Recently uploaded (20)

Intellectual Property Right (Jurisprudence).pptx
Intellectual Property Right (Jurisprudence).pptx
Vishal Chanalia
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
Vitamin and Nutritional Deficiencies.pptx
Vitamin and Nutritional Deficiencies.pptx
Vishal Chanalia
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
jutaydeonne
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
Aprendendo Arquitetura Framework Salesforce - Dia 02
Aprendendo Arquitetura Framework Salesforce - Dia 02
Mauricio Alexandre Silva
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
Values Education 10 Quarter 1 Module .pptx
Values Education 10 Quarter 1 Module .pptx
JBPafin
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
IIT Kharagpur Quiz Club
 
Intellectual Property Right (Jurisprudence).pptx
Intellectual Property Right (Jurisprudence).pptx
Vishal Chanalia
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
ENGLISH_Q1_W1 PowerPoint grade 3 quarter 1 week 1
jutaydeonne
 
Vitamin and Nutritional Deficiencies.pptx
Vitamin and Nutritional Deficiencies.pptx
Vishal Chanalia
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
Q1_ENGLISH_PPT_WEEK 1 power point grade 3 Quarter 1 week 1
jutaydeonne
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
University of Ghana Cracks Down on Misconduct: Over 100 Students Sanctioned
Kweku Zurek
 
Aprendendo Arquitetura Framework Salesforce - Dia 02
Aprendendo Arquitetura Framework Salesforce - Dia 02
Mauricio Alexandre Silva
 
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
 
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
Photo chemistry Power Point Presentation
Photo chemistry Power Point Presentation
mprpgcwa2024
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
Values Education 10 Quarter 1 Module .pptx
Values Education 10 Quarter 1 Module .pptx
JBPafin
 
Pests of Maize: An comprehensive overview.pptx
Pests of Maize: An comprehensive overview.pptx
Arshad Shaikh
 
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
ENGLISH-5 Q1 Lesson 1.pptx - Story Elements
Mayvel Nadal
 
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
LAZY SUNDAY QUIZ "A GENERAL QUIZ" JUNE 2025 SMC QUIZ CLUB, SILCHAR MEDICAL CO...
Ultimatewinner0342
 
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
IIT Kharagpur Quiz Club
 
Ad

Tuples in Python

  • 2. Tuple Introduction A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list or even a tuple.  Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by commas. Like list and string, elements of a tuple can be accessed using index values, starting from 0. >>> tuple = () # Empty Tuple >>> Tuple = (1) # Tuple with single element >>> tuple1 = (1,2,3,4,5) # tuple of integers >>> tuple2 =('Economics',87,'Accountancy',89.6) # tuple of mixed data types NOTE: If we assign the value without comma it is treated as integer. It should be noted that a sequence without parenthesis is treated as tuple by default.
  • 3. Creation of Tuple tuple() function is used to create a tuple from other sequences. Tuple Creation from List : Tuple creation from String : Tuple creation from input() Tuple creation using eval() : for Ex: Tuple = eval(input(“Enter elements”))
  • 4. Elements of a tuple can be accessed in the same way as a list or string using indexing and slicing. >>> tuple1 = (2,4,6,8,10,12) # returns the first element of tuple1 >>> tuple1[0] # returns fourth element of tuple1 2 >>> tuple1[3] 8 >>> tuple1[15] # returns error as index is out of range IndexError: tuple index out of range index >>> tuple1[1+4] # an expression resulting in an integer 12 >>> tuple1[-1] # returns first element from right 12 NOTE: Tuple is an immutable data type. It means that the elements of a tuple cannot be changed Accessing Elements in a Tuple
  • 5. Concatenation It allows to join tuples using concatenation operator depicted by symbol +. We can also create a new tuple which contains the result of this concatenation operation. >>> tuple1 = (1,3,5,7,9) >>> tuple2 = (2,4,6,8,10) >>> tuple1 + tuple2 # concatenates two tuples (1, 3, 5, 7, 9, 2, 4, 6, 8, 10) Concatenation operator (+) can also be used for extending an existing tuple. When we extend a tuple using concatenation a new tuple is created. >>> tuple3(1, 2, 3, 4, 5, 6) # more than one elements are appended >>> tuple4 = tuple3 + (7,8,9) >>> tuple4 (1, 2, 3, 4, 5, 6, 7, 8, 9) Repetition It is denoted by the symbol *(asterisk). It is used to repeat elements of a tuple. We can repeat the tuple elements. The repetition operator requires the first operand to be a tuple and the second operand to be an integer only. >>> tuple1 = ('Hello','World') >>> tuple1 * 2 #tuple with single element ('Hello', 'World', 'Hello', 'World’) Tuple Operations
  • 6. Membership The in operator checks if the element is present in the tuple and returns True, else it returns False. >>> tuple1 = ('Red','Green','Blue') >>> 'Green' in tuple1 True The not in operator returns True if the element is not present in the tuple, else it returns False. >>> tuple1 = ('Red','Green','Blue') >>> 'Green' not in tuple1 False Slicing Like string and list, slicing can be applied to tuples also. >>> tuple1 = (10,20,30,40,50,60,70,80) # tuple1 is a tuple >>> tuple1[2:7] (30, 40, 50, 60, 70) # elements from index 2 to index 6 >>> tuple1[0:len(tuple1)] # all elements of tuple are printed (10, 20, 30, 40, 50, 60, 70, 80) >>> tuple1[:5] (10, 20, 30, 40, 50) # slice starts from zero index >>> tuple1[2:] (30, 40, 50, 60, 70, 80) # slice is till end of the tuple
  • 7. Tuple Deletion Tuple unpacking Error shown because deletion of a single element is also possible. Complete tuple has been deleted. Now error shown on printing of tuple.
  • 8. Method Description Example len() Returns the length or the number of elements of the tuple passed as the argument >>> tuple1 = (10,20,30,40,50) >>> len(tuple1) 5 tuple() Creates an empty tuple if no argument is passed Creates a tuple if a sequence is passed as argument >>> tuple1 = tuple() >>> tuple1 ( ) >>> tuple1 = tuple('aeiou') #string >>> tuple1 ('a', 'e', 'i', 'o', 'u') >>> tuple2 = tuple([1,2,3]) #list >>> tuple2 (1, 2, 3) >>> tuple3 = tuple(range(5)) >>> tuple3 (0, 1, 2, 3, 4) count() Returns the number of times the given element appears in the tuple >>> tuple1 = (10,20,30,10,40,10,50) >>> tuple1.count(10) 3 >>> tuple1.count(90) 0 Tuple Methods and Built-in Functions
  • 9. Method Description Example index() Returns the index of the first occurrence of the element in the given tuple >>> tuple1 = (10,20,30,40,50) >>> tuple1.index(30) 2 >>> tuple1.index(90) ValueError: tuple.index(x): x not in tuple sorted() Takes elements in the tuple and returns a new sorted list. It should be noted that, sorted() does not make any change to the original tuple >>> tuple1 = ("Rama","Heena","Raj", "Mohsin","Aditya") >>> sorted(tuple1) ['Aditya', 'Heena', 'Mohsin', 'Raj', 'Rama'] min() max() sum() Returns minimum or smallest element of the tuple Returns maximum or largest element of the tuple Returns sum of the elements of the tuple >>> tuple1 = (19,12,56,18,9,87,34) >>> min(tuple1) 9 >>> max(tuple1) 87 >>> sum(tuple1) 235
  • 10. A tuple inside another tuple is called a nested tuple. In the given program, roll number, name and marks (in percentage) of students are saved in a tuple. To store details of many such students we can create a nested tuple #Create a nested tuple to store roll number, name and marks of students To store records of students in tuple and print them st=((101,"Aman",98),(102,"Geet",95),(103,"Sahil",87),(104,"Pawan",79)) print("S_No"," Roll_No"," Name"," Marks") for i in range(0,len(st)): print((i+1),'t',st[i][0],'t',st[i][1],'t',st[i][2]) Output: S_No Roll_No Name Marks 1 101 Aman 98 2 102 Geet 95 3 103 Sahil 87 4 104 Pawan 79 Nested Tuples
  • 11. Write a program to swap two numbers without using a temporary variable. #Program to swap two numbers num1 = int(input('Enter the first number: ')) num2 = int(input('Enter the second number: ')) print("nNumbers before swapping:") print("First Number:",num1) print("Second Number:",num2) (num1,num2) = (num2,num1) print("nNumbers after swapping:") print("First Number:",num1) print("Second Number:",num2) Output: Enter the first number: 5 Enter the second number: 10 Numbers before swapping: First Number: 5 Second Number: 10 Numbers after swapping: First Number: 10 Second Number: 5
  • 12. Write a program to compute the area and circumference of a circle using a function. def circle(r): # Function to compute area and circumference of the circle area = 3.14*r*r circumference = 2*3.14*r # returns a tuple having two elements area and circumference return (area, circumference) # end of function radius = int(input('Enter radius of circle: ')) area, circumference = circle(radius) print('Area of circle is:', area) print('Circumference of circle is : ', circumference) Output: Enter radius of circle: 5 Area of circle is: 78.5 Circumference of circle is: 31.400000000000002
  • 13. Print the maximum and minimum number from this tuple. numbers = tuple() #create an empty tuple 'numbers' n = int(input("How many numbers you want to enter?: ")) for i in range(0,n): num = int(input()) # it will assign numbers entered by user to tuple 'numbers’ numbers = numbers +(num,) print('nThe numbers in the tuple are:') print(numbers) print("nThe maximum number is:") print(max(numbers)) print("The minimum number is:") print(min(numbers)) Output: How many numbers do you want to enter? : 5 9 8 10 12 15 The numbers in the tuple are: (9, 8, 10, 12, 15) The maximum number is : 15 The minimum number is : 8