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

PPTX
Passing an Array to a Function (ICT Programming)
PDF
Tuples in Python
PDF
Python list
PPT
Array in Java
PPTX
Tuple in python
PPTX
Chapter 16 Dictionaries
PDF
03 Linear Arrays Memory Representations .pdf
PPTX
Python variables and data types.pptx
Passing an Array to a Function (ICT Programming)
Tuples in Python
Python list
Array in Java
Tuple in python
Chapter 16 Dictionaries
03 Linear Arrays Memory Representations .pdf
Python variables and data types.pptx

What's hot (20)

PPTX
Pointer in c
PDF
Java arrays
PPT
Strings
PDF
Python Dictionary
PPTX
Looping Statements and Control Statements in Python
PPT
Multidimensional array in C
DOC
Jumping statements
PPTX
PDF
Python strings
PDF
What is Range Function? | Range in Python Explained | Edureka
PPTX
String Manipulation in Python
ODP
Python Modules
PPTX
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
PPTX
Python array
PDF
Pointers
PPTX
Python for loop
PPTX
If else statement in c++
PPTX
Inheritance in c++
PPTX
Pointers in c language
Pointer in c
Java arrays
Strings
Python Dictionary
Looping Statements and Control Statements in Python
Multidimensional array in C
Jumping statements
Python strings
What is Range Function? | Range in Python Explained | Edureka
String Manipulation in Python
Python Modules
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Python array
Pointers
Python for loop
If else statement in c++
Inheritance in c++
Pointers in c language
Ad

Similar to Pytho_tuples (20)

PPTX
Python Lecture 11
PPTX
List_tuple_dictionary.pptx
PPTX
Python list tuple dictionary presentation
PPTX
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
PPTX
PRESENTATION ON TUPLES.pptx
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PDF
STRING LIST TUPLE DICTIONARY FILE.pdf
PDF
Python tuples and Dictionary
PPTX
Tuples-and-Dictionaries.pptx
PPTX
Chapter 3-Data structure in python programming.pptx
DOCX
Python Materials- Lists, Dictionary, Tuple
PDF
Python-Tuples
PDF
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
PDF
python_avw - Unit-03.pdf
PDF
ESIT135 Problem Solving Using Python Notes of Unit-3
PPTX
Lists.pptx
PPTX
58. Tuples python ppt that will help you understand concept of tuples
PPTX
Lists_tuples.pptx
PPTX
Python Collections
Python Lecture 11
List_tuple_dictionary.pptx
Python list tuple dictionary presentation
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
PRESENTATION ON TUPLES.pptx
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
STRING LIST TUPLE DICTIONARY FILE.pdf
Python tuples and Dictionary
Tuples-and-Dictionaries.pptx
Chapter 3-Data structure in python programming.pptx
Python Materials- Lists, Dictionary, Tuple
Python-Tuples
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
python_avw - Unit-03.pdf
ESIT135 Problem Solving Using Python Notes of Unit-3
Lists.pptx
58. Tuples python ppt that will help you understand concept of tuples
Lists_tuples.pptx
Python Collections
Ad

More from BMS Institute of Technology and Management (14)

PDF
Artificial Neural Networks: Introduction, Neural Network representation, Appr...
PPTX
Decision Tree Learning: Decision tree representation, Appropriate problems fo...
PPTX
Classification: MNIST, training a Binary classifier, performance measure, mul...
PPTX
ML_Module1.Introduction_and_conceprtLearning_pptx.pptx
PDF
Software Engineering and Introduction, Activities and ProcessModels
PDF
Python Regular Expressions
PDF
PPTX
Introduction to the Python
DOCX
15CS562 AI VTU Question paper
PPTX
PPT
Problems, Problem spaces and Search
PDF
Introduction to Artificial Intelligence and few examples
Artificial Neural Networks: Introduction, Neural Network representation, Appr...
Decision Tree Learning: Decision tree representation, Appropriate problems fo...
Classification: MNIST, training a Binary classifier, performance measure, mul...
ML_Module1.Introduction_and_conceprtLearning_pptx.pptx
Software Engineering and Introduction, Activities and ProcessModels
Python Regular Expressions
Introduction to the Python
15CS562 AI VTU Question paper
Problems, Problem spaces and Search
Introduction to Artificial Intelligence and few examples

Recently uploaded (20)

PDF
Integrating Fractal Dimension and Time Series Analysis for Optimized Hyperspe...
PDF
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
PDF
86236642-Electric-Loco-Shed.pdf jfkduklg
PDF
A SYSTEMATIC REVIEW OF APPLICATIONS IN FRAUD DETECTION
PPT
Occupational Health and Safety Management System
PPTX
UNIT - 3 Total quality Management .pptx
PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
Visual Aids for Exploratory Data Analysis.pdf
PPTX
Fundamentals of Mechanical Engineering.pptx
PDF
PPT on Performance Review to get promotions
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
introduction to high performance computing
PPTX
Nature of X-rays, X- Ray Equipment, Fluoroscopy
PDF
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
PDF
Abrasive, erosive and cavitation wear.pdf
PPT
introduction to datamining and warehousing
PPTX
Current and future trends in Computer Vision.pptx
PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PDF
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF
Integrating Fractal Dimension and Time Series Analysis for Optimized Hyperspe...
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
86236642-Electric-Loco-Shed.pdf jfkduklg
A SYSTEMATIC REVIEW OF APPLICATIONS IN FRAUD DETECTION
Occupational Health and Safety Management System
UNIT - 3 Total quality Management .pptx
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
Visual Aids for Exploratory Data Analysis.pdf
Fundamentals of Mechanical Engineering.pptx
PPT on Performance Review to get promotions
R24 SURVEYING LAB MANUAL for civil enggi
Automation-in-Manufacturing-Chapter-Introduction.pdf
introduction to high performance computing
Nature of X-rays, X- Ray Equipment, Fluoroscopy
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
Abrasive, erosive and cavitation wear.pdf
introduction to datamining and warehousing
Current and future trends in Computer Vision.pptx
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
Level 2 – IBM Data and AI Fundamentals (1)_v1.1.PDF

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.