SlideShare a Scribd company logo
MODULE 3 – PART 3
TUPLES
By,
Ravi Kumar B N
Assistant professor, Dept. of CSE
BMSIT & M
WHAT IS A TUPLE?
A tuple is a sequence of values much like a list which can be represented using
parenthesis ( ) with comma separator.
The values stored in a tuple can be any type and they are indexed by integers.
The important difference is that tuples are immutable.
Example : #creating a tuple
a = (‘ruby’, ‘java')
#another approach
b = ‘EEE' , ‘ME'
print(a)
print(b)
Output: (‘ruby' , ‘java’)
(‘EEE' , ‘ME')
CONTD..
➢Tuples are also comparable and hashable so we can sort lists of them and use tuples
as key values in Python dictionaries.
➢If our data is fixed and never changes then we should go for Tuple.
➢ Insertion Order is preserved
➢ Duplicates are allowed
➢Heterogeneous objects are allowed.
➢ Tuple support both +ve and -ve index.
+ve index forward direction(from left to right)
-ve index means backward direction(from right to left)
t=10,20,30,40
print(t)
print(type(t))
#Output :
(10, 20, 30, 40)
<class 'tuple'>
#Empty tuple
t=()
print(type(t))
#Output :
<class 'tuple'>
TUPLES ARE IMMUTABLE
Once we creates tuple, we cannot change its content. Hence tuple objects are immutable.
Eg:
To create a tuple with a single element, you have to include a final comma:
A value in parentheses is not a tuple:
t=(10,20,30,40)
t [1]=70
TypeError: 'tuple' object does not support item assignment
>>> t1 = 'a',
>>> type(t1)
<class 'tuple'>
Valid Tuples
1. t=()
2. t=10,20,30,40
3. t=10,
4. t=(10,)
5. t=(10,20,30,40)
>>> t2 = ('a')
>>> type(t2)
<class 'str'>
>>> t2 = (10)
>>> type(t2)
<class 'int'>
CREATING TUPLES
There are 2 ways of creating tuples
Using parenthesis
1. t=()
creation of empty tuple
2. t=(10,)
t=10,
creation of single valued tuple ,parenthesis are
optional ,should end with comma
3. t=10,20,30
t=(10,20,30)
creation of multi values tuples & parenthesis
are optional
Using tuple() –Function
list=[10,20,30]
t=tuple(list)
print(t)
#Output: (10,20,30)
t=tuple(range(10,20,2))
print(t)
#Output: (10,12,14,16,18)
t = tuple('lupins')
print( t)
#Output : ('l', 'u', 'p', 'i', 'n', 's')
ACCESSING ELEMENTS OF TUPLE
1. Using indexing
t=(10,20,30,40,50,60)
print(t[0]) #10
print(t[-1]) #60
print(t[100]) #IndexError: tuple index out of range
t[0]= 25 #TypeError: object doesn't support item assignment
2. By using slice operator:
t=(10,20,30,40,50,60)
print(t[2:5])
print(t[2:100])
print(t[-5:-2])
Output : (30, 40, 50)
(30, 40, 50, 60)
(20,30,40)
-6 -5 -4 -3 -2 -1
10 20 30 40 50 60
0 1 2 3 4 5
MATHEMATICAL OPERATORS
1. Concatenation (+)
2. Multiplication (*)
3. Relational (< > <= >= == !=)
4. Membership (in and not in)
Concatenation
t1=(10,20,30)
t2=(40,50,60)
t3=t1+ t2
print(t3)
Output:
(10,20,30,40,50,60)
Multiplication
t1=(10,20,30)
t2=t1*3
print(t2)
Output:
(10,20,30,10,20,30,10,20,30)
Relational (Comparing):
compares the first element from each
sequence. It goes on to the next elements
until it finds elements that differ.
Subsequent elements are not considered
(even if they are really big).
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
>>> (10,13)==(10,19)
False
>>> (10,13)==(10,13)
True
Membership (in and not in)
>>> t1=(10, 12, 14, 16, 18)
>>> 10 in t1
True
>>> 17 in t1
False
>>> 17 not in t1
True
>>> 'a' in tuple('string')
False
>>> 'n' in tuple('string')
True
TUPLE FUNCTIONS [FOR REFERNCE]
len() Returns the length or the number of elements >>> tuple1 = (10,20,30,40,50)
>>> len(tuple1)
5
tuple() Creates a tuple if a sequence is passed as argument >>> tuple2 = tuple([1,2,3]) #list
>>> tuple2
(1, 2, 3)
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
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
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")
>>> sorted(tuple1)
['Heena', 'Raj', 'Rama']
min()
max()
sum()
Returns minimum element of the tuple
Returns maximum 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
TUPLE ASSIGNMENT
One of the unique syntactic features of the Python language is the ability to have a tuple on the left side of an assignment
statement. This allows you to assign more than one variable at a time when the left side is a sequence.
In this example we have a two-element list (which is a sequence) and assign the first and second elements of the
sequence to the variables x and y in a single statement.
>>> m = ('have', 'fun’ )
• OR
>>> x, y = m
>>> x
'have'
>>> y
'fun'
>>> x = m[0]
>>> y = m[1]
>>> x
'have'
>>> y
'fun'
>>> addr = 'monty@python.org'
>>> uname, domain = addr.split('@')
The return value from split is a list with two
elements; the first element is assigned to uname,
the second to domain.
>>> print(uname) #monty
>>> print(domain) #python.org
The number of variables on the left
and the number of values on the
right must be the same:
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
A particularly clever application of
tuple assignment allows us to swap
the values of two variables in a
single statement:
>>> a, b = b, a
SORTING IN TUPLES- LISTS OF TUPLES
The sort function works in this way. It sorts primarily by first element, but in the case
of a tie, it sorts by second element, and so on.
This feature lends itself to a pattern called DSU for
Decorate a sequence by building a list of tuples with one or more sort keys preceding
the elements from the sequence,
Sort the list of tuples using the Python built-in sort, and
Undecorate by extracting the sorted elements of the sequence.
SAMPLE#sample list
>>> t=[1,2,3]
>>> t.append(4)
>>> t
[1, 2, 3, 4]
#append a tuple into a list
>>> t.append((2,5))
>>> t
[1, 2, 3, 4, (2, 5)]
#creating a list of tuples - exapmle1
>>> t1=[(21,'w'),(39,'x'),(19,'y')]
>>> t1
[(21, 'w'), (39, 'x'), (19, 'y’)]
#sorting list of tuples
>>> t1.sort()
>>> t1
[(19, 'y'), (21, 'w'), (39, 'x’)]
#sorting reverse
>>> t1.sort(reverse=True)
>>> t1
[(39, 'x'), (21, 'w'), (19, 'y’)]
#example2
>>> t2=[(19,'z'),(21,'w'),(39,'x'),(19,'y’)]
>>> t2.sort()
>>> t2
[(19, 'y'), (19, 'z'), (21, 'w'), (39, 'x')]
>>> t2.sort(reverse=True)
>>> t2
[(39, 'x'), (21, 'w'), (19, 'z'), (19, 'y’)]
#example3
>>> m=[('akash','24.5'),('nikil','18.2'),('anand','4.2')]
>>> m
[('akash', '24.5'), ('nikil', '18.2'), ('anand', '4.2')]
>>> m.sort()
>>> m
[('akash', '24.5'), ('anand', '4.2'), ('nikil', '18.2')]
>>> m.sort(reverse=True)
>>> m
[('nikil', '18.2'), ('anand', '4.2'), ('akash', '24.5')]
txt = 'but soft what light in yonder window breaks'
words = txt.split()
t = list()
for word in words:
t.append((len(word), word))
print(t)
t.sort(reverse=True)
print(t)
res = list()
for length, word in t:
res.append(word)
print(“Sorted list from longest to shortestn” res)
#Output:
# finding the length for each word and printing it
[(3, 'but'), (4, 'soft'), (4, 'what'), (5, 'light'), (2, 'in'), (6, 'yonder'), (6, 'window'), (6, 'breaks’)]
#printing list in reverse order
[(6, 'yonder'), (6, 'window'), (6, 'breaks'), (5, 'light'), (4, 'what'), (4, 'soft'), (3, 'but'), (2, 'in’)]
#printing only words according to problem statement
Sorted list from longest to shortest
['yonder', 'window', 'breaks', 'light', 'what', 'soft', 'but', 'in']
WRITE A PROGRAM TO DISPLAY A LIST OF WORDS FROM LONGEST TO
SHORTEST
WRITE A PROGRAM TO FIND MOST COMMONLY
USED WORDS IN A TEXT FILE.
import string
fhand = open(‘sample.txt')
counts = dict()
for line in fhand:
line = line.translate(str.maketrans('', '',string.punctuation))
line = line.lower()
for word in line.split():
if word not in counts:
counts[word] = 1
else:
counts[word] += 1
lst = list()
for key, val in list(counts.items()):
lst.append((val, key))
lst.sort(reverse=True)
for key, val in lst[:10]:
print(key, val)
Output
4 tuples
4 lists
2 use
2 tuple
2 the
2 is
2 as
2 are
2 and
2 a
#sample.txt
A tuple is an immutable sequence of Python objects.
Tuples are sequences, just like lists.
The differences between tuples and lists are, the tuples cannot
be changed unlike lists and tuples use parentheses,
whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-
separated values.
DIFFERENCES BETWEEN LIST AND TUPLE:
List Tuple
List objects are mutable Tuple objects are immutable.
insertion order is preserved, duplicate objects are
allowed, heterogeneous objects are allowed, index
and slicing are supported.
insertion order is preserved, duplicate objects are
allowed, heterogeneous objects are allowed, index
and slicing are supported.
List is a Group of Comma separated Values within
Square Brackets and Square Brackets are
mandatory. Eg: i = [10, 20, 30, 40]
Tuple is a Group of Comma separated Values within
Parenthesis and Parenthesis are optional.
Eg: t = (10, 20, 30, 40) t = 10, 20, 30, 40
If the Content is not fixed and keep on changing then
we should go for List.
If the content is fixed and never changes then we
should go for Tuple.
List Objects can not used as Keys for Dictionaries
because Keys should be Hashable and Immutable.
Tuple objects can be used as Keys for Dictionaries
because Keys should be Hashable and Immutable.
TUPLES AND DICTIONARIES
Dictionaries have a method called items() that returns a list of tuples, where each tuple is a key-
value pair:
# from dictionary to list of tuples
>>> d = {'a':10, 'b':1, 'c':22}
>>> t = list(d.items())
>>> print(t)
[('b', 1), ('a', 10), ('c', 22)]
As you should expect from a dictionary, the items are in no particular order. However, since the
list of tuples is a list, and tuples are comparable, we can now sort the list of tuples.
Converting a dictionary to a list of tuples is a way for us to output the contents of a dictionary
sorted by key:
>>> t.sort()
>>> t
[('a', 10), ('b', 1), ('c', 22)]
#The new list is sorted in ascending alphabetical order by the key value.
MULTIPLE ASSIGNMENT WITH DICTIONARIES
➢ We can combine the method items(), tuple assignment and a for-loop to get a pattern for
traversing dictionary:
➢This loop has two iteration variables because items() returns a list of tuples.
➢And key, val is a tuple assignment that successively iterates through each of the key-value pairs
in the dictionary.
➢ For each iteration through the loop, both key and value are advanced to the next key-value
pair in the dictionary in hash order.
d={'Tom': 1292, 'Jerry': 3501, 'Donald': 8913}
for key, val in list(d.items()):
print(val,key)
Output:
1292 Tom
3501 Jerry
8913 Donald
CONTD..
Once we get a key-value pair, we can create a list of tuples and sort them
➢ In the above program, we are extracting key, val pair from the dictionary and appending it to the
list
➢ While appending, we are putting inner parentheses to make sure that each pair is treated as a
tuple.
➢ Then, we are sorting the list in the descending order.
d={'Tom': 9291, 'Jerry': 3501, 'Donald': 8913} ls=list()
for key, val in d.items():
ls.append((val,key)) #observe inner parentheses
print("List of tuples:",ls)
ls.sort(reverse=True)
print("List of sorted tuples:",ls)
The output would be –
List of tuples:
[(9291, 'Tom'), (3501, 'Jerry'), (8913, 'Donald')]
List of sorted tuples:
[(9291, 'Tom'), (8913, 'Donald'), (3501, 'Jerry')]
USING TUPLES AS KEYS IN DICTIONARIES
As tuples and dictionaries are hashable, when we want a dictionary containing
composite keys, we will use tuples.
We wanted to create a telephone directory that maps from last-name, first-name pairs to
telephone numbers.
Write a dictionary assignment statement as follows:
directory[last,first] = number
The expression in brackets is a tuple. We could use tuple assignment in a for loop to
traverse this dictionary.
for last, first in directory:
print(first, last, directory[last,first])
This loop traverses the keys in directory, which are tuples. It assigns the elements of
each tuple to last and first, then prints the name and corresponding telephone number.
>>> di={('r','b'):90,('c','s'):98}
>>> di
{('r', 'b'): 90, ('c', 's'): 98}
>>> for fname,lname in di:
print(di[fname,lname])
90
98
>>> for fname,lname in di:
print(fname,lname, di[fname,lname])
r b 90
c s 98
>>> for fname,lname in di:
print(fname,lname,"=", di[fname,lname])
r b = 90
c s = 98
SUMMARY ON SEQUENCES: STRINGS, LISTS AND TUPLES
1. Strings are more limited compared to other sequences like lists and Tuples.
Because, the elements in strings must be characters only. Moreover, strings are
immutable. Hence, if we need to modify the characters in a sequence, it is better to
go for a list of characters than a string.
2. As lists are mutable, they are most common compared to tuples. But, in some
situations as given below, tuples are preferable.
a. When we have a return statement from a function, it is better to use tuples rather
than lists.
b. When a dictionary key must be a sequence of elements, then we must use
immutable type like strings and tuples
c. When a sequence of elements is being passed to a function as arguments, usage of
tuples reduces unexpected behaviour due to aliasing.
3. As tuples are immutable, the methods like sort() and reverse() cannot be applied
on them. But, Python provides built-in functions sorted() and reversed() which will
take a sequence as an argument and return a new sequence with modified results.
TUPLES WONT SUPPORT
SORT():
>>> t1=(10,29,12,45)
>>> t1.sort()
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
t1.sort()
AttributeError: 'tuple' object has no attribute 'sort'
>>> sorted(t1)
[10, 12, 29, 45]
>>> list(reversed(t1))
[45, 12, 29, 10]
ASSIGNMENT:
1) WAP create a telephone directory where name of a person is Firstname- last
name pair and value is the telephone number by using Tuples as Keys in
Dictionary.
Ex: names=(('Tom','Cat'),('Jerry','Mouse'), ('Donald', 'Duck'))
Tel number=[3561, 4014, 9813]
2) Compare and contrast strings, lists, dictionaries and tuples.
THANK
YOU

More Related Content

What's hot

List in Python
List in PythonList in Python
List in Python
Siddique Ibrahim
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
S.M. Salaquzzaman
 
Python list
Python listPython list
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
1. python
1. python1. python
1. python
PRASHANT OJHA
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Python list
Python listPython list
Python list
Mohammed Sikander
 
Lists
ListsLists
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
Aswini Dharmaraj
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
Praveen M Jigajinni
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
narmadhakin
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
Inzamam Baig
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
Prof. Dr. K. Adisesha
 
LIST IN PYTHON
LIST IN PYTHONLIST IN PYTHON
LIST IN PYTHON
vikram mahendra
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
Praveen M Jigajinni
 

What's hot (20)

List in Python
List in PythonList in Python
List in Python
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
 
Python list
Python listPython list
Python list
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
1. python
1. python1. python
1. python
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Python list
Python listPython list
Python list
 
Lists
ListsLists
Lists
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
 
LIST IN PYTHON
LIST IN PYTHONLIST IN PYTHON
LIST IN PYTHON
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 

Similar to Pytho_tuples

List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
ChandanVatsa2
 
PRESENTATION ON TUPLES.pptx
PRESENTATION ON TUPLES.pptxPRESENTATION ON TUPLES.pptx
PRESENTATION ON TUPLES.pptx
rohan899711
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
omprakashmeena48
 
Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptxTuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
AyushTripathi998357
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
DPS Ranipur Haridwar UK
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
Krishna Nanda
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
Asst.prof M.Gokilavani
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
AshaWankar1
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
Yagna15
 
Lists_tuples.pptx
Lists_tuples.pptxLists_tuples.pptx
Lists_tuples.pptx
M Vishnuvardhan Reddy
 
Python Collections
Python CollectionsPython Collections
Python Collections
sachingarg0
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
GaganRaj28
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
vikram mahendra
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
Asst.prof M.Gokilavani
 
updated_tuple_in_python.pdf
updated_tuple_in_python.pdfupdated_tuple_in_python.pdf
updated_tuple_in_python.pdf
Koteswari Kasireddy
 
Python Tuple.pdf
Python Tuple.pdfPython Tuple.pdf
Python Tuple.pdf
T PRIYA
 
Data types in python
Data types in pythonData types in python
Data types in python
RaginiJain21
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
RamiHarrathi1
 

Similar to Pytho_tuples (20)

List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
PRESENTATION ON TUPLES.pptx
PRESENTATION ON TUPLES.pptxPRESENTATION ON TUPLES.pptx
PRESENTATION ON TUPLES.pptx
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptxTuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
Lists_tuples.pptx
Lists_tuples.pptxLists_tuples.pptx
Lists_tuples.pptx
 
Python Collections
Python CollectionsPython Collections
Python Collections
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Module-2.pptx
Module-2.pptxModule-2.pptx
Module-2.pptx
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
updated_tuple_in_python.pdf
updated_tuple_in_python.pdfupdated_tuple_in_python.pdf
updated_tuple_in_python.pdf
 
Python Tuple.pdf
Python Tuple.pdfPython Tuple.pdf
Python Tuple.pdf
 
Data types in python
Data types in pythonData types in python
Data types in python
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 

More from BMS Institute of Technology and Management

Software Engineering and Introduction, Activities and ProcessModels
Software Engineering and Introduction, Activities and ProcessModels Software Engineering and Introduction, Activities and ProcessModels
Software Engineering and Introduction, Activities and ProcessModels
BMS Institute of Technology and Management
 
File handling in Python
File handling in PythonFile handling in Python
Introduction to the Python
Introduction to the PythonIntroduction to the Python
Introduction to the Python
BMS Institute of Technology and Management
 
15CS562 AI VTU Question paper
15CS562 AI VTU Question paper15CS562 AI VTU Question paper
15CS562 AI VTU Question paper
BMS Institute of Technology and Management
 
weak slot and filler
weak slot and fillerweak slot and filler
strong slot and filler
strong slot and fillerstrong slot and filler
Problems, Problem spaces and Search
Problems, Problem spaces and SearchProblems, Problem spaces and Search
Problems, Problem spaces and Search
BMS Institute of Technology and Management
 
Introduction to Artificial Intelligence and few examples
Introduction to Artificial Intelligence and few examplesIntroduction to Artificial Intelligence and few examples
Introduction to Artificial Intelligence and few examples
BMS Institute of Technology and Management
 

More from BMS Institute of Technology and Management (8)

Software Engineering and Introduction, Activities and ProcessModels
Software Engineering and Introduction, Activities and ProcessModels Software Engineering and Introduction, Activities and ProcessModels
Software Engineering and Introduction, Activities and ProcessModels
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Introduction to the Python
Introduction to the PythonIntroduction to the Python
Introduction to the Python
 
15CS562 AI VTU Question paper
15CS562 AI VTU Question paper15CS562 AI VTU Question paper
15CS562 AI VTU Question paper
 
weak slot and filler
weak slot and fillerweak slot and filler
weak slot and filler
 
strong slot and filler
strong slot and fillerstrong slot and filler
strong slot and filler
 
Problems, Problem spaces and Search
Problems, Problem spaces and SearchProblems, Problem spaces and Search
Problems, Problem spaces and Search
 
Introduction to Artificial Intelligence and few examples
Introduction to Artificial Intelligence and few examplesIntroduction to Artificial Intelligence and few examples
Introduction to Artificial Intelligence and few examples
 

Recently uploaded

cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
SakkaravarthiShanmug
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
Hematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood CountHematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood Count
shahdabdulbaset
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
PKavitha10
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
ecqow
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Sinan KOZAK
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
Madan Karki
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
architagupta876
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
GauravCar
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 

Recently uploaded (20)

cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
Hematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood CountHematology Analyzer Machine - Complete Blood Count
Hematology Analyzer Machine - Complete Blood Count
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
 
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
Optimizing Gradle Builds - Gradle DPE Tour Berlin 2024
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Manufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptxManufacturing Process of molasses based distillery ppt.pptx
Manufacturing Process of molasses based distillery ppt.pptx
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
AI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptxAI assisted telemedicine KIOSK for Rural India.pptx
AI assisted telemedicine KIOSK for Rural India.pptx
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
artificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptxartificial intelligence and data science contents.pptx
artificial intelligence and data science contents.pptx
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 

Pytho_tuples

  • 1. MODULE 3 – PART 3 TUPLES By, Ravi Kumar B N Assistant professor, Dept. of CSE BMSIT & M
  • 2. WHAT IS A TUPLE? A tuple is a sequence of values much like a list which can be represented using parenthesis ( ) with comma separator. The values stored in a tuple can be any type and they are indexed by integers. The important difference is that tuples are immutable. Example : #creating a tuple a = (‘ruby’, ‘java') #another approach b = ‘EEE' , ‘ME' print(a) print(b) Output: (‘ruby' , ‘java’) (‘EEE' , ‘ME')
  • 3. CONTD.. ➢Tuples are also comparable and hashable so we can sort lists of them and use tuples as key values in Python dictionaries. ➢If our data is fixed and never changes then we should go for Tuple. ➢ Insertion Order is preserved ➢ Duplicates are allowed ➢Heterogeneous objects are allowed. ➢ Tuple support both +ve and -ve index. +ve index forward direction(from left to right) -ve index means backward direction(from right to left) t=10,20,30,40 print(t) print(type(t)) #Output : (10, 20, 30, 40) <class 'tuple'> #Empty tuple t=() print(type(t)) #Output : <class 'tuple'>
  • 4. TUPLES ARE IMMUTABLE Once we creates tuple, we cannot change its content. Hence tuple objects are immutable. Eg: To create a tuple with a single element, you have to include a final comma: A value in parentheses is not a tuple: t=(10,20,30,40) t [1]=70 TypeError: 'tuple' object does not support item assignment >>> t1 = 'a', >>> type(t1) <class 'tuple'> Valid Tuples 1. t=() 2. t=10,20,30,40 3. t=10, 4. t=(10,) 5. t=(10,20,30,40) >>> t2 = ('a') >>> type(t2) <class 'str'> >>> t2 = (10) >>> type(t2) <class 'int'>
  • 5. CREATING TUPLES There are 2 ways of creating tuples Using parenthesis 1. t=() creation of empty tuple 2. t=(10,) t=10, creation of single valued tuple ,parenthesis are optional ,should end with comma 3. t=10,20,30 t=(10,20,30) creation of multi values tuples & parenthesis are optional Using tuple() –Function list=[10,20,30] t=tuple(list) print(t) #Output: (10,20,30) t=tuple(range(10,20,2)) print(t) #Output: (10,12,14,16,18) t = tuple('lupins') print( t) #Output : ('l', 'u', 'p', 'i', 'n', 's')
  • 6. ACCESSING ELEMENTS OF TUPLE 1. Using indexing t=(10,20,30,40,50,60) print(t[0]) #10 print(t[-1]) #60 print(t[100]) #IndexError: tuple index out of range t[0]= 25 #TypeError: object doesn't support item assignment 2. By using slice operator: t=(10,20,30,40,50,60) print(t[2:5]) print(t[2:100]) print(t[-5:-2]) Output : (30, 40, 50) (30, 40, 50, 60) (20,30,40) -6 -5 -4 -3 -2 -1 10 20 30 40 50 60 0 1 2 3 4 5
  • 7. MATHEMATICAL OPERATORS 1. Concatenation (+) 2. Multiplication (*) 3. Relational (< > <= >= == !=) 4. Membership (in and not in) Concatenation t1=(10,20,30) t2=(40,50,60) t3=t1+ t2 print(t3) Output: (10,20,30,40,50,60) Multiplication t1=(10,20,30) t2=t1*3 print(t2) Output: (10,20,30,10,20,30,10,20,30) Relational (Comparing): compares the first element from each sequence. It goes on to the next elements until it finds elements that differ. Subsequent elements are not considered (even if they are really big). >>> (0, 1, 2) < (0, 3, 4) True >>> (0, 1, 2000000) < (0, 3, 4) True >>> (10,13)==(10,19) False >>> (10,13)==(10,13) True Membership (in and not in) >>> t1=(10, 12, 14, 16, 18) >>> 10 in t1 True >>> 17 in t1 False >>> 17 not in t1 True >>> 'a' in tuple('string') False >>> 'n' in tuple('string') True
  • 8. TUPLE FUNCTIONS [FOR REFERNCE] len() Returns the length or the number of elements >>> tuple1 = (10,20,30,40,50) >>> len(tuple1) 5 tuple() Creates a tuple if a sequence is passed as argument >>> tuple2 = tuple([1,2,3]) #list >>> tuple2 (1, 2, 3) 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 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 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") >>> sorted(tuple1) ['Heena', 'Raj', 'Rama'] min() max() sum() Returns minimum element of the tuple Returns maximum 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
  • 9. TUPLE ASSIGNMENT One of the unique syntactic features of the Python language is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence. In this example we have a two-element list (which is a sequence) and assign the first and second elements of the sequence to the variables x and y in a single statement. >>> m = ('have', 'fun’ ) • OR >>> x, y = m >>> x 'have' >>> y 'fun' >>> x = m[0] >>> y = m[1] >>> x 'have' >>> y 'fun' >>> addr = 'monty@python.org' >>> uname, domain = addr.split('@') The return value from split is a list with two elements; the first element is assigned to uname, the second to domain. >>> print(uname) #monty >>> print(domain) #python.org The number of variables on the left and the number of values on the right must be the same: >>> a, b = 1, 2, 3 ValueError: too many values to unpack A particularly clever application of tuple assignment allows us to swap the values of two variables in a single statement: >>> a, b = b, a
  • 10. SORTING IN TUPLES- LISTS OF TUPLES The sort function works in this way. It sorts primarily by first element, but in the case of a tie, it sorts by second element, and so on. This feature lends itself to a pattern called DSU for Decorate a sequence by building a list of tuples with one or more sort keys preceding the elements from the sequence, Sort the list of tuples using the Python built-in sort, and Undecorate by extracting the sorted elements of the sequence.
  • 11. SAMPLE#sample list >>> t=[1,2,3] >>> t.append(4) >>> t [1, 2, 3, 4] #append a tuple into a list >>> t.append((2,5)) >>> t [1, 2, 3, 4, (2, 5)] #creating a list of tuples - exapmle1 >>> t1=[(21,'w'),(39,'x'),(19,'y')] >>> t1 [(21, 'w'), (39, 'x'), (19, 'y’)] #sorting list of tuples >>> t1.sort() >>> t1 [(19, 'y'), (21, 'w'), (39, 'x’)] #sorting reverse >>> t1.sort(reverse=True) >>> t1 [(39, 'x'), (21, 'w'), (19, 'y’)] #example2 >>> t2=[(19,'z'),(21,'w'),(39,'x'),(19,'y’)] >>> t2.sort() >>> t2 [(19, 'y'), (19, 'z'), (21, 'w'), (39, 'x')] >>> t2.sort(reverse=True) >>> t2 [(39, 'x'), (21, 'w'), (19, 'z'), (19, 'y’)] #example3 >>> m=[('akash','24.5'),('nikil','18.2'),('anand','4.2')] >>> m [('akash', '24.5'), ('nikil', '18.2'), ('anand', '4.2')] >>> m.sort() >>> m [('akash', '24.5'), ('anand', '4.2'), ('nikil', '18.2')] >>> m.sort(reverse=True) >>> m [('nikil', '18.2'), ('anand', '4.2'), ('akash', '24.5')]
  • 12. txt = 'but soft what light in yonder window breaks' words = txt.split() t = list() for word in words: t.append((len(word), word)) print(t) t.sort(reverse=True) print(t) res = list() for length, word in t: res.append(word) print(“Sorted list from longest to shortestn” res) #Output: # finding the length for each word and printing it [(3, 'but'), (4, 'soft'), (4, 'what'), (5, 'light'), (2, 'in'), (6, 'yonder'), (6, 'window'), (6, 'breaks’)] #printing list in reverse order [(6, 'yonder'), (6, 'window'), (6, 'breaks'), (5, 'light'), (4, 'what'), (4, 'soft'), (3, 'but'), (2, 'in’)] #printing only words according to problem statement Sorted list from longest to shortest ['yonder', 'window', 'breaks', 'light', 'what', 'soft', 'but', 'in'] WRITE A PROGRAM TO DISPLAY A LIST OF WORDS FROM LONGEST TO SHORTEST
  • 13. WRITE A PROGRAM TO FIND MOST COMMONLY USED WORDS IN A TEXT FILE. import string fhand = open(‘sample.txt') counts = dict() for line in fhand: line = line.translate(str.maketrans('', '',string.punctuation)) line = line.lower() for word in line.split(): if word not in counts: counts[word] = 1 else: counts[word] += 1 lst = list() for key, val in list(counts.items()): lst.append((val, key)) lst.sort(reverse=True) for key, val in lst[:10]: print(key, val) Output 4 tuples 4 lists 2 use 2 tuple 2 the 2 is 2 as 2 are 2 and 2 a #sample.txt A tuple is an immutable sequence of Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different comma- separated values.
  • 14. DIFFERENCES BETWEEN LIST AND TUPLE: List Tuple List objects are mutable Tuple objects are immutable. insertion order is preserved, duplicate objects are allowed, heterogeneous objects are allowed, index and slicing are supported. insertion order is preserved, duplicate objects are allowed, heterogeneous objects are allowed, index and slicing are supported. List is a Group of Comma separated Values within Square Brackets and Square Brackets are mandatory. Eg: i = [10, 20, 30, 40] Tuple is a Group of Comma separated Values within Parenthesis and Parenthesis are optional. Eg: t = (10, 20, 30, 40) t = 10, 20, 30, 40 If the Content is not fixed and keep on changing then we should go for List. If the content is fixed and never changes then we should go for Tuple. List Objects can not used as Keys for Dictionaries because Keys should be Hashable and Immutable. Tuple objects can be used as Keys for Dictionaries because Keys should be Hashable and Immutable.
  • 15. TUPLES AND DICTIONARIES Dictionaries have a method called items() that returns a list of tuples, where each tuple is a key- value pair: # from dictionary to list of tuples >>> d = {'a':10, 'b':1, 'c':22} >>> t = list(d.items()) >>> print(t) [('b', 1), ('a', 10), ('c', 22)] As you should expect from a dictionary, the items are in no particular order. However, since the list of tuples is a list, and tuples are comparable, we can now sort the list of tuples. Converting a dictionary to a list of tuples is a way for us to output the contents of a dictionary sorted by key: >>> t.sort() >>> t [('a', 10), ('b', 1), ('c', 22)] #The new list is sorted in ascending alphabetical order by the key value.
  • 16. MULTIPLE ASSIGNMENT WITH DICTIONARIES ➢ We can combine the method items(), tuple assignment and a for-loop to get a pattern for traversing dictionary: ➢This loop has two iteration variables because items() returns a list of tuples. ➢And key, val is a tuple assignment that successively iterates through each of the key-value pairs in the dictionary. ➢ For each iteration through the loop, both key and value are advanced to the next key-value pair in the dictionary in hash order. d={'Tom': 1292, 'Jerry': 3501, 'Donald': 8913} for key, val in list(d.items()): print(val,key) Output: 1292 Tom 3501 Jerry 8913 Donald
  • 17. CONTD.. Once we get a key-value pair, we can create a list of tuples and sort them ➢ In the above program, we are extracting key, val pair from the dictionary and appending it to the list ➢ While appending, we are putting inner parentheses to make sure that each pair is treated as a tuple. ➢ Then, we are sorting the list in the descending order. d={'Tom': 9291, 'Jerry': 3501, 'Donald': 8913} ls=list() for key, val in d.items(): ls.append((val,key)) #observe inner parentheses print("List of tuples:",ls) ls.sort(reverse=True) print("List of sorted tuples:",ls) The output would be – List of tuples: [(9291, 'Tom'), (3501, 'Jerry'), (8913, 'Donald')] List of sorted tuples: [(9291, 'Tom'), (8913, 'Donald'), (3501, 'Jerry')]
  • 18. USING TUPLES AS KEYS IN DICTIONARIES As tuples and dictionaries are hashable, when we want a dictionary containing composite keys, we will use tuples. We wanted to create a telephone directory that maps from last-name, first-name pairs to telephone numbers. Write a dictionary assignment statement as follows: directory[last,first] = number The expression in brackets is a tuple. We could use tuple assignment in a for loop to traverse this dictionary. for last, first in directory: print(first, last, directory[last,first]) This loop traverses the keys in directory, which are tuples. It assigns the elements of each tuple to last and first, then prints the name and corresponding telephone number.
  • 19. >>> di={('r','b'):90,('c','s'):98} >>> di {('r', 'b'): 90, ('c', 's'): 98} >>> for fname,lname in di: print(di[fname,lname]) 90 98 >>> for fname,lname in di: print(fname,lname, di[fname,lname]) r b 90 c s 98 >>> for fname,lname in di: print(fname,lname,"=", di[fname,lname]) r b = 90 c s = 98
  • 20. SUMMARY ON SEQUENCES: STRINGS, LISTS AND TUPLES 1. Strings are more limited compared to other sequences like lists and Tuples. Because, the elements in strings must be characters only. Moreover, strings are immutable. Hence, if we need to modify the characters in a sequence, it is better to go for a list of characters than a string. 2. As lists are mutable, they are most common compared to tuples. But, in some situations as given below, tuples are preferable. a. When we have a return statement from a function, it is better to use tuples rather than lists. b. When a dictionary key must be a sequence of elements, then we must use immutable type like strings and tuples c. When a sequence of elements is being passed to a function as arguments, usage of tuples reduces unexpected behaviour due to aliasing. 3. As tuples are immutable, the methods like sort() and reverse() cannot be applied on them. But, Python provides built-in functions sorted() and reversed() which will take a sequence as an argument and return a new sequence with modified results.
  • 21. TUPLES WONT SUPPORT SORT(): >>> t1=(10,29,12,45) >>> t1.sort() Traceback (most recent call last): File "<pyshell#52>", line 1, in <module> t1.sort() AttributeError: 'tuple' object has no attribute 'sort' >>> sorted(t1) [10, 12, 29, 45] >>> list(reversed(t1)) [45, 12, 29, 10]
  • 22. ASSIGNMENT: 1) WAP create a telephone directory where name of a person is Firstname- last name pair and value is the telephone number by using Tuples as Keys in Dictionary. Ex: names=(('Tom','Cat'),('Jerry','Mouse'), ('Donald', 'Duck')) Tel number=[3561, 4014, 9813] 2) Compare and contrast strings, lists, dictionaries and tuples.