際際滷

際際滷Share a Scribd company logo
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Python Programming
Dr. S. P. Ponnusamy
Assistant Professor and Head
1
Unit  3
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Syllabus
 UNIT III
Tuples  creation  basic tuple operations  tuple() function 
indexing  slicing  built-in functions used on tuples  tuple
methods  packing  unpacking  traversing of tuples 
populating tuples  zip() function - Sets  Traversing of sets 
set methods  frozenset.
.
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
3
Tuples
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples - Introduction
 Tuple is a collection of objects that are ordered, immutable, finite, and
heterogeneous (different types of objects).
 The tuples have fixed sizes.
 Tuples are used when the programmer wants to store multiples of
different data types under a single name.
 It can also be used to return multiple items from the function.
 The elements of the tuple cannot be altered as strings (both are
immutable).
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples - Creation
 The tuple is created with elements covered by a pair of opening and
closing parenthesis.
 An empty tuple is created with empty parenthesis.
 The individual elements of tuples are called "items."
>>> myTuple = (1, 2.0, 4.67, "Chandru", 'M')
>>> myTuple
(1, 2.0, 4.67, 'Chandru', 'M')
>>> myTuple=()
>>> myTuple
()
>>>type(myTuple)
<class 'tuple'>
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples - Creation
 The tuple is created with elements covered by a pair of opening and
closing parenthesis.
 An empty tuple is created with empty parenthesis.
 The individual elements of tuples are called "items."
>>> myTuple = (1, 2.0, 4.67, "Chandru", 'M')
>>> myTuple
(1, 2.0, 4.67, 'Chandru', 'M')
>>> myTuple=()
>>> myTuple
()
>>>type(myTuple)
<class 'tuple'>
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples - Creation
 Covering the elements in parenthesis is not mandatory.
 That means, the elements are assigned to tuples with comma separation
only.
>>> myTuple = 1, 2.0, 4.67, "Chandru", 'M'
>>> myTuple
(1, 2.0, 4.67, 'Chandru', 'M)
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples - Creation
 A tuple with single item creation is problem in Python as per the above
examples.
 A single item covered by parenthesis is considered to be its own base
type.
>>> myTuple=(8)
>>> myTuple
8
>>> type(myTuple)
<class 'int'>
>>> myTuple =("u")
>>> myTuple
'u'
type(myTuple)
<class 'str'>
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples - Creation
 A tuple with a single item can be created in a special way.
 The elements should be covered with or without parenthesis, but an
additional comma must be placed at the end.
>>> myTuple=(8,)
>>> myTuple
(8,)
>>> type(myTuple)
<class 'tuple'>
>>> myTuple=("God",)
>>> myTuple
('God',)
>>> type(myTuple)
<class 'tuple'>
>>> myTuple=8,
>>> myTuple
(8,)
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
10
Basic Tuple operations
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples operations - Concatenation
 The tuple concatenation operation is done by the "+" (plus) operator.
 Two or more tuples can be concatenated using the plus operator .
>>> myTuple1=(1,2.4,"ABC")
>>> myTuple2=(111.23,-12,"xyz",23)
>>> myTuple3=myTuple1+myTuple2
>>> myTuple3
(1, 2.4, 'ABC', 111.23, -12, 'xyz', 23)
>>> (12,"University",33.8)+(23,345.12)
(12, 'University', 33.8, 23, 345.12)
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples operations - Repetition
 You must be careful when you apply tuple concatenation.
 The other type of value cannot be concatenated with tuple literals using
the concatenation operator.
 If you try this, the interpreter will raise a TypeError message.
>>>(12,"University",33.8)+ 8
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
(12,"University",33.8)+ 8
TypeError: can only concatenate tuple (not "int") to
tuple
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples operations - Repetition
 The given tuple is repeated for the given number of times using the *
(multiplication) operator.
 The operator requires the tuple as the first operand and an integer value
(the number of times to be repeated) as the second operand.
>>> (1,2,3,"Apple")*3
(1, 2, 3, 'Apple', 1, 2, 3, 'Apple', 1, 2, 3, 'Apple')
>>> (1,2,3,"Apple")*2 +(3,5,23.1)
(1, 2, 3, 'Apple', 1, 2, 3, 'Apple', 3, 5, 23.1)
 Tuple concatenation can be applied along with the tuple repetition.
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples operations  Member operator - in
 The member operators are used to check the existence of the given
value in the tuple or not.
 The operator in returns True when the given value exists in a tuple, else
it returns False. It is a binary operator.
>>> myTuple1=(111.23,-12,"xyz",23)
>>> 23 in myTuple1
True
>>> 42 in myTuple1
False
>>> "xyz" in myTuple1
True
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples operations  Member operator - not in
 The operator not in returns True when the value does not exist in the
tuple, else it returns False.
 It works opposite to the in operator.
>>> myTuple1=(111.23,-12,"xyz",23)
>>> 42 not in myTuple1
True
>>> 23 not in myTuple1
False
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples operations  Comparison
 The comparison operations on tuples are done with the help of the
relational operators ==. !=, <, >, <=, >=.
 These operators can be applied only to tuple literals and variables.
 Python compares the tuples' values one by one on both sides.
>>> myTuple1=(111.23,-12,"xyz",23)
>>> myTuple2=(111.23,-12,"xyz",23)
>>> myTuple1==myTuple2
True
>>> myTuple1>myTuple2
False
>>> myTuple2=(123,-12,34)
>>> myTuple1<myTuple2
True
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
17
Tuple() function
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples function  tuple()
 It is a built-in function used to create a tuple or convert an iterable
object into a tuple.
 The iterable objects are list, string, set, and dictionary.
>>> tuple("University") #converts string into tuple
('U', 'n', 'i', 'v', 'e', 'r', 's', 'i', 't', 'y')
>>> tuple([1,2,3,"xyz"]) #converts list into tuple
(1, 2, 3, 'xyz')
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Tuples function  tuple()
>>> s1={1,2,3,4}
>>> t1=tuple(s1) # converting set into tuple
>>> t1
(1, 2, 3, 4)
>>> tuple({1:"Apple",2:"Mango"}) #converts dictionary
into tuple
(1, 2)
>>> d1={1:"Apple",2:"Mango"} #converts dictionary items
into tuple
>>> tuple(d1.items())
((1, 'Apple'), (2, 'Mango'))
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
20
Indexing and slicing
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Indexing
 The tuple elements can be accessed by using the indexing operator.
 You can access individual elements by single indexing.
 The Python allows both positive and negative indexing on tuples.
 The positive indexing starts at 0 and ends at n-1, where n is the length of
the tuple.
 The negative indexing starts at -1 and ends at -n.
 The positive indexing follows a left-to-right order, whereas the negative
indexing follows a right-to-left order.
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Indexing
>>> myTuple=(11,23.5,-44,'xyz')
>>> myTuple[2]
-44
>>> myTuple[0]
11
>>> myTuple[-3]
23.5
>>> myTuple[3]
'xyz'
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Slicing
 A subset or slice of a tuple can be extracted by using the index operator
as in a string.
 The index operator takes three parameters, which are separated by a
colon.
 The parameters are the desired start and end indexing values as well as
an optional step value.
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Indexing
>>> myTuple[-3:-1]
(78.98, 'xyz')
>>> myTuple[-4:]
(-34, 78.98, 'xyz', 8)
>>> myTuple[:-2]
(23, -34, 78.98)
>>> myTuple[:]
(23, -34, 78.98, 'xyz', 8)
>>>
(23, -34, 78.98, 'xyz', 8)
>>> myTuple=(23,-34,78.98,"xyz",8)
>>> len(myTuple)
5
>>> myTuple[1:3]
(-34, 78.98)
>>> myTuple[:4]
(23, -34, 78.98, 'xyz')
>>> myTuple[2:]
(78.98, 'xyz', 8)
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
25
Built-in Functions
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Built-in Functions
Function Description
len(tuple) Gives the total length of the tuple.
max(tuple) Returns item from the numerical tuple with max value.
min(tuple) Returns item from the numerical tuple with min value.
sum(tuple)
Gives the sum of the elements present in the numerical
tuple as an output
tuple(seq) Converts an iterable object into tuple.
(already discussed in section 6.4)
sorted(tuple) Returns a sorted list as an output of a numerical tuple in
ascending order
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
27
Tuple Methods
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Methods
Function Description
tuple.count(value) Returns the number of times a specified value occurs in a tuple
if found. If not found, returns 0.
tuple.index(value) Returns the location of where a specified value was found after
searching the tuple for it. If the specified value is not found, it
returns error message.
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
Methods
>>> myTuple1=(13,-34,88,23.5,78,'xyz',88)
>>> myTuple1.count(13)
1
>>> myTuple1.count(88)
2
>>> myTuple1.count(99)
0
>>> myTuple1.index(78)
4
>>> myTuple1.index(103)
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
myTuple1.index(103)
ValueError: tuple.index(x): x not in tuple
Government Arts and Science College
Tittagudi  606 106
Department of Computer Science
Python Programming
30
End
Ad

Recommended

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
Tuples in Python
Tuples in Python
DPS Ranipur Haridwar UK
Python-Tuples
Python-Tuples
Krishna Nanda
Python tuple
Python tuple
Mohammed Sikander
Tuple in python
Tuple in python
vikram mahendra
updated_tuple_in_python.pdf
updated_tuple_in_python.pdf
Koteswari Kasireddy
014 TUPLES.pdf
014 TUPLES.pdf
amman23
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
TUPLE.ppt
TUPLE.ppt
UnknownPerson930271
Unit-4 Basic Concepts of Tuple in Python .pptx
Unit-4 Basic Concepts of Tuple in Python .pptx
SwapnaliGawali5
Tuple.py
Tuple.py
nuripatidar
Tuples in Python Object Oriented Programming.pptx
Tuples in Python Object Oriented Programming.pptx
MuhammadZuhairArfeen
Python Tuple.pdf
Python Tuple.pdf
T PRIYA
Pytho_tuples
Pytho_tuples
BMS Institute of Technology and Management
1.2 - Tuplesforthepythonlearnersino.pptx
1.2 - Tuplesforthepythonlearnersino.pptx
IstarthaPD
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 tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
AyushTripathi998357
tupple.pptx
tupple.pptx
satyabratPanda2
UNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptx
harikahhy
tuple in python is an impotant topic.pptx
tuple in python is an impotant topic.pptx
urvashipundir04
Chapter 13 Tuples.pptx
Chapter 13 Tuples.pptx
IshaanRay1
Tuple Operation and Tuple Assignment in Python.pdf
Tuple Operation and Tuple Assignment in Python.pdf
THIRUGAMING1
tuples chapter (1).pdfhsuenduneudhhsbhhd
tuples chapter (1).pdfhsuenduneudhhsbhhd
megaladsmegala
Chapter 13 Tuples.pptx
Chapter 13 Tuples.pptx
vinnisart
Programming in Python Lists and its methods .ppt
Programming in Python Lists and its methods .ppt
Dr. Jasmine Beulah Gnanadurai
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801

More Related Content

Similar to Python programming UNIT III-Part-2.0.pptx (20)

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
TUPLE.ppt
TUPLE.ppt
UnknownPerson930271
Unit-4 Basic Concepts of Tuple in Python .pptx
Unit-4 Basic Concepts of Tuple in Python .pptx
SwapnaliGawali5
Tuple.py
Tuple.py
nuripatidar
Tuples in Python Object Oriented Programming.pptx
Tuples in Python Object Oriented Programming.pptx
MuhammadZuhairArfeen
Python Tuple.pdf
Python Tuple.pdf
T PRIYA
Pytho_tuples
Pytho_tuples
BMS Institute of Technology and Management
1.2 - Tuplesforthepythonlearnersino.pptx
1.2 - Tuplesforthepythonlearnersino.pptx
IstarthaPD
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 tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
AyushTripathi998357
tupple.pptx
tupple.pptx
satyabratPanda2
UNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptx
harikahhy
tuple in python is an impotant topic.pptx
tuple in python is an impotant topic.pptx
urvashipundir04
Chapter 13 Tuples.pptx
Chapter 13 Tuples.pptx
IshaanRay1
Tuple Operation and Tuple Assignment in Python.pdf
Tuple Operation and Tuple Assignment in Python.pdf
THIRUGAMING1
tuples chapter (1).pdfhsuenduneudhhsbhhd
tuples chapter (1).pdfhsuenduneudhhsbhhd
megaladsmegala
Chapter 13 Tuples.pptx
Chapter 13 Tuples.pptx
vinnisart
Programming in Python Lists and its methods .ppt
Programming in Python Lists and its methods .ppt
Dr. Jasmine Beulah Gnanadurai
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
Tuples in Python Object Oriented Programming.pptx
Tuples in Python Object Oriented Programming.pptx
MuhammadZuhairArfeen
Python Tuple.pdf
Python Tuple.pdf
T PRIYA
1.2 - Tuplesforthepythonlearnersino.pptx
1.2 - Tuplesforthepythonlearnersino.pptx
IstarthaPD
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 tuples and Dictionary
Python tuples and Dictionary
Aswini Dharmaraj
UNIT-3 python and data structure alo.pptx
UNIT-3 python and data structure alo.pptx
harikahhy
tuple in python is an impotant topic.pptx
tuple in python is an impotant topic.pptx
urvashipundir04
Chapter 13 Tuples.pptx
Chapter 13 Tuples.pptx
IshaanRay1
Tuple Operation and Tuple Assignment in Python.pdf
Tuple Operation and Tuple Assignment in Python.pdf
THIRUGAMING1
tuples chapter (1).pdfhsuenduneudhhsbhhd
tuples chapter (1).pdfhsuenduneudhhsbhhd
megaladsmegala
Chapter 13 Tuples.pptx
Chapter 13 Tuples.pptx
vinnisart

Recently uploaded (20)

YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 6-14-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
Code Profiling in Odoo 18 - Odoo 18 際際滷s
Code Profiling in Odoo 18 - Odoo 18 際際滷s
Celine George
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
mprpgcwa2024
How to use search fetch method in Odoo 18
How to use search fetch method in Odoo 18
Celine George
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
Learning Styles Inventory for Senior High School Students
Learning Styles Inventory for Senior High School Students
Thelma Villaflores
Romanticism in Love and Sacrifice An Analysis of Oscar Wildes The Nightingal...
Romanticism in Love and Sacrifice An Analysis of Oscar Wildes The Nightingal...
KaryanaTantri21
How to Customize Quotation Layouts in Odoo 18
How to Customize Quotation Layouts in Odoo 18
Celine George
How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
June 2025 Progress Update With Board Call_In process.pptx
June 2025 Progress Update With Board Call_In process.pptx
International Society of Service Innovation Professionals
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
Wage and Salary Computation.ppt.......,x
Wage and Salary Computation.ppt.......,x
JosalitoPalacio
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
IIT Kharagpur Quiz Club
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
Q1_TLE 8_Week 1- Day 1 tools and equipment
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
INDUCTIVE EFFECT slide for first prof pharamacy students
INDUCTIVE EFFECT slide for first prof pharamacy students
SHABNAM FAIZ
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
Filipino 9 Maikling Kwento Ang Ama Panitikang Asiyano
sumadsadjelly121997
Code Profiling in Odoo 18 - Odoo 18 際際滷s
Code Profiling in Odoo 18 - Odoo 18 際際滷s
Celine George
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
GREAT QUIZ EXCHANGE 2025 - GENERAL QUIZ.pptx
Ronisha Das
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
F-BLOCK ELEMENTS POWER POINT PRESENTATIONS
mprpgcwa2024
How to use search fetch method in Odoo 18
How to use search fetch method in Odoo 18
Celine George
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
Learning Styles Inventory for Senior High School Students
Learning Styles Inventory for Senior High School Students
Thelma Villaflores
Romanticism in Love and Sacrifice An Analysis of Oscar Wildes The Nightingal...
Romanticism in Love and Sacrifice An Analysis of Oscar Wildes The Nightingal...
KaryanaTantri21
How to Customize Quotation Layouts in Odoo 18
How to Customize Quotation Layouts in Odoo 18
Celine George
How to Manage Different Customer Addresses in Odoo 18 Accounting
How to Manage Different Customer Addresses in Odoo 18 Accounting
Celine George
Hurricane Helene Application Documents Checklists
Hurricane Helene Application Documents Checklists
Mebane Rash
Wage and Salary Computation.ppt.......,x
Wage and Salary Computation.ppt.......,x
JosalitoPalacio
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
Great Governors' Send-Off Quiz 2025 Prelims IIT KGP
IIT Kharagpur Quiz Club
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
Q1_TLE 8_Week 1- Day 1 tools and equipment
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
INDUCTIVE EFFECT slide for first prof pharamacy students
INDUCTIVE EFFECT slide for first prof pharamacy students
SHABNAM FAIZ
Ad

Python programming UNIT III-Part-2.0.pptx

  • 1. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Python Programming Dr. S. P. Ponnusamy Assistant Professor and Head 1 Unit 3
  • 2. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Syllabus UNIT III Tuples creation basic tuple operations tuple() function indexing slicing built-in functions used on tuples tuple methods packing unpacking traversing of tuples populating tuples zip() function - Sets Traversing of sets set methods frozenset. .
  • 3. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming 3 Tuples
  • 4. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples - Introduction Tuple is a collection of objects that are ordered, immutable, finite, and heterogeneous (different types of objects). The tuples have fixed sizes. Tuples are used when the programmer wants to store multiples of different data types under a single name. It can also be used to return multiple items from the function. The elements of the tuple cannot be altered as strings (both are immutable).
  • 5. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples - Creation The tuple is created with elements covered by a pair of opening and closing parenthesis. An empty tuple is created with empty parenthesis. The individual elements of tuples are called "items." >>> myTuple = (1, 2.0, 4.67, "Chandru", 'M') >>> myTuple (1, 2.0, 4.67, 'Chandru', 'M') >>> myTuple=() >>> myTuple () >>>type(myTuple) <class 'tuple'>
  • 6. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples - Creation The tuple is created with elements covered by a pair of opening and closing parenthesis. An empty tuple is created with empty parenthesis. The individual elements of tuples are called "items." >>> myTuple = (1, 2.0, 4.67, "Chandru", 'M') >>> myTuple (1, 2.0, 4.67, 'Chandru', 'M') >>> myTuple=() >>> myTuple () >>>type(myTuple) <class 'tuple'>
  • 7. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples - Creation Covering the elements in parenthesis is not mandatory. That means, the elements are assigned to tuples with comma separation only. >>> myTuple = 1, 2.0, 4.67, "Chandru", 'M' >>> myTuple (1, 2.0, 4.67, 'Chandru', 'M)
  • 8. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples - Creation A tuple with single item creation is problem in Python as per the above examples. A single item covered by parenthesis is considered to be its own base type. >>> myTuple=(8) >>> myTuple 8 >>> type(myTuple) <class 'int'> >>> myTuple =("u") >>> myTuple 'u' type(myTuple) <class 'str'>
  • 9. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples - Creation A tuple with a single item can be created in a special way. The elements should be covered with or without parenthesis, but an additional comma must be placed at the end. >>> myTuple=(8,) >>> myTuple (8,) >>> type(myTuple) <class 'tuple'> >>> myTuple=("God",) >>> myTuple ('God',) >>> type(myTuple) <class 'tuple'> >>> myTuple=8, >>> myTuple (8,)
  • 10. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming 10 Basic Tuple operations
  • 11. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples operations - Concatenation The tuple concatenation operation is done by the "+" (plus) operator. Two or more tuples can be concatenated using the plus operator . >>> myTuple1=(1,2.4,"ABC") >>> myTuple2=(111.23,-12,"xyz",23) >>> myTuple3=myTuple1+myTuple2 >>> myTuple3 (1, 2.4, 'ABC', 111.23, -12, 'xyz', 23) >>> (12,"University",33.8)+(23,345.12) (12, 'University', 33.8, 23, 345.12)
  • 12. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples operations - Repetition You must be careful when you apply tuple concatenation. The other type of value cannot be concatenated with tuple literals using the concatenation operator. If you try this, the interpreter will raise a TypeError message. >>>(12,"University",33.8)+ 8 Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> (12,"University",33.8)+ 8 TypeError: can only concatenate tuple (not "int") to tuple
  • 13. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples operations - Repetition The given tuple is repeated for the given number of times using the * (multiplication) operator. The operator requires the tuple as the first operand and an integer value (the number of times to be repeated) as the second operand. >>> (1,2,3,"Apple")*3 (1, 2, 3, 'Apple', 1, 2, 3, 'Apple', 1, 2, 3, 'Apple') >>> (1,2,3,"Apple")*2 +(3,5,23.1) (1, 2, 3, 'Apple', 1, 2, 3, 'Apple', 3, 5, 23.1) Tuple concatenation can be applied along with the tuple repetition.
  • 14. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples operations Member operator - in The member operators are used to check the existence of the given value in the tuple or not. The operator in returns True when the given value exists in a tuple, else it returns False. It is a binary operator. >>> myTuple1=(111.23,-12,"xyz",23) >>> 23 in myTuple1 True >>> 42 in myTuple1 False >>> "xyz" in myTuple1 True
  • 15. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples operations Member operator - not in The operator not in returns True when the value does not exist in the tuple, else it returns False. It works opposite to the in operator. >>> myTuple1=(111.23,-12,"xyz",23) >>> 42 not in myTuple1 True >>> 23 not in myTuple1 False
  • 16. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples operations Comparison The comparison operations on tuples are done with the help of the relational operators ==. !=, <, >, <=, >=. These operators can be applied only to tuple literals and variables. Python compares the tuples' values one by one on both sides. >>> myTuple1=(111.23,-12,"xyz",23) >>> myTuple2=(111.23,-12,"xyz",23) >>> myTuple1==myTuple2 True >>> myTuple1>myTuple2 False >>> myTuple2=(123,-12,34) >>> myTuple1<myTuple2 True
  • 17. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming 17 Tuple() function
  • 18. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples function tuple() It is a built-in function used to create a tuple or convert an iterable object into a tuple. The iterable objects are list, string, set, and dictionary. >>> tuple("University") #converts string into tuple ('U', 'n', 'i', 'v', 'e', 'r', 's', 'i', 't', 'y') >>> tuple([1,2,3,"xyz"]) #converts list into tuple (1, 2, 3, 'xyz')
  • 19. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Tuples function tuple() >>> s1={1,2,3,4} >>> t1=tuple(s1) # converting set into tuple >>> t1 (1, 2, 3, 4) >>> tuple({1:"Apple",2:"Mango"}) #converts dictionary into tuple (1, 2) >>> d1={1:"Apple",2:"Mango"} #converts dictionary items into tuple >>> tuple(d1.items()) ((1, 'Apple'), (2, 'Mango'))
  • 20. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming 20 Indexing and slicing
  • 21. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Indexing The tuple elements can be accessed by using the indexing operator. You can access individual elements by single indexing. The Python allows both positive and negative indexing on tuples. The positive indexing starts at 0 and ends at n-1, where n is the length of the tuple. The negative indexing starts at -1 and ends at -n. The positive indexing follows a left-to-right order, whereas the negative indexing follows a right-to-left order.
  • 22. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Indexing >>> myTuple=(11,23.5,-44,'xyz') >>> myTuple[2] -44 >>> myTuple[0] 11 >>> myTuple[-3] 23.5 >>> myTuple[3] 'xyz'
  • 23. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Slicing A subset or slice of a tuple can be extracted by using the index operator as in a string. The index operator takes three parameters, which are separated by a colon. The parameters are the desired start and end indexing values as well as an optional step value.
  • 24. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Indexing >>> myTuple[-3:-1] (78.98, 'xyz') >>> myTuple[-4:] (-34, 78.98, 'xyz', 8) >>> myTuple[:-2] (23, -34, 78.98) >>> myTuple[:] (23, -34, 78.98, 'xyz', 8) >>> (23, -34, 78.98, 'xyz', 8) >>> myTuple=(23,-34,78.98,"xyz",8) >>> len(myTuple) 5 >>> myTuple[1:3] (-34, 78.98) >>> myTuple[:4] (23, -34, 78.98, 'xyz') >>> myTuple[2:] (78.98, 'xyz', 8)
  • 25. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming 25 Built-in Functions
  • 26. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Built-in Functions Function Description len(tuple) Gives the total length of the tuple. max(tuple) Returns item from the numerical tuple with max value. min(tuple) Returns item from the numerical tuple with min value. sum(tuple) Gives the sum of the elements present in the numerical tuple as an output tuple(seq) Converts an iterable object into tuple. (already discussed in section 6.4) sorted(tuple) Returns a sorted list as an output of a numerical tuple in ascending order
  • 27. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming 27 Tuple Methods
  • 28. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Methods Function Description tuple.count(value) Returns the number of times a specified value occurs in a tuple if found. If not found, returns 0. tuple.index(value) Returns the location of where a specified value was found after searching the tuple for it. If the specified value is not found, it returns error message.
  • 29. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming Methods >>> myTuple1=(13,-34,88,23.5,78,'xyz',88) >>> myTuple1.count(13) 1 >>> myTuple1.count(88) 2 >>> myTuple1.count(99) 0 >>> myTuple1.index(78) 4 >>> myTuple1.index(103) Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> myTuple1.index(103) ValueError: tuple.index(x): x not in tuple
  • 30. Government Arts and Science College Tittagudi 606 106 Department of Computer Science Python Programming 30 End