SlideShare a Scribd company logo
Aswini D
Assistant Professor
Tuples
Aswini D
Assistant Professor
Tuples are sequences, just like lists.
A tuple contains a sequence of items of any data type
The difference between the tuple and list is that we
cannot change the elements of a tuple once it is assigned
whereas in a list, elements can be changed.
Elements in the tuples are fixed
Once it is created, we cannot add or remove elements
Hence tuples are immutable
Since, tuples are quite similar to lists, both of them are used
in similar situations as well.
However, there are certain advantages of implementing a
tuple over a list.
Tuples that contain immutable elements can be used as
key for a dictionary.With list, this is not possible.
If you have data that doesn't change, implementing it as
tuple will guarantee that it remains write-protected.
 A tuple is created by placing all the items (elements) inside a parentheses (),
separated by comma.
 The parentheses are optional but is a good practice to write it.
 A tuple can have any number of items and they may be of different types (integer,
float, list, string etc.).
# empty tule
T1=()
# tuples having of integers
T2 = (1, 2, 3)
# tuple with mixed datatypes
T3 = (1, "Hello", 3.4)
# nested tuple
T4 = (“welcome", (8, 4, 6))
Method -1
Method-2
# empty tuple
T1= tuple()
# tuple function with string as
arguments
my_list = tuple(“welcome”)
• Creating a tuple with one
element is a bit tricky.
• Single element should be
followed by comma
>>> T1=(4)
>>> type(T1)
<class 'int'>
>>> T1=(4,)
>>> type(T1)
<class 'tuple'>
we can access the elements of a tuple using
index & slice operator
Indexing
 We can use the index operator [] to access an item in a tuple
where the index starts from 0.
>>> t1=(10,20,30)
>>> print(t1[2])
30
>>> print(t1[-3])
10
Slicing
 We can access a range of items in a tuple by using the slicing
operator - colon ":“
>>>print(t1[0:2:1])
(10, 20)
#nested tuple
>>> t1=(10,20,(15,25))
>>> print(t1[2][0])
15
 Unlike lists, tuples are immutable.
 This means that elements of a tuple cannot be changed once it has been
assigned.
>>> t1=(5,10,15,[50,90])
>>> t1[0]=100
TypeError: 'tuple' object does not support item assignment
But, if the element is itself a mutable datatype like list, its nested items can be
changed.
>>> t1[3][1]=100
>>> print(t1)
(5, 10, 15, [50, 100])
 Tuples are immutable which means you cannot add elements to
tuple
 Removing individual tuple elements is not possible.
 To explicitly remove an entire tuple, just use the del statement
>>> del t1
>>> t1
NameError: name 't1' is not defined
Description Python
Expression
Results
Concatenation (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6)
Repetition ('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!')
Membership 3 in (1, 2, 3) True
Iteration for x in (1, 2, 3):
print x,
1 2 3
Method Description
count(x)
Return the number of items that is equal
to x
index(x)
Return index of first item that is equal
to x
Function Description
all()
Return True if all elements of the tuple are true (or if the tuple is
empty).
any()
Return True if any element of the tuple is true. If the tuple is empty,
return False.
len() Return the length (the number of items) in the tuple.
max() Return the largest item in the tuple.
min() Return the smallest item in the tuple
sorted()
Take elements in the tuple and return a new sorted list (does not sort
the tuple itself).
sum() Return the sum of all elements in the tuple.
Method 1-using sorted() function
>>>t1=(95.5,25.8,2.6,10)
>>> t2=tuple(sorted(t1))
>>>print(t2)
(2.6, 10, 25.8, 95.5)
Method 2
Tuple does not contain sort() method. so to
sort tuple, it can be converted into list, then
sort the list, again convert the sorted list into
tuple
Program:
t1=(95.5,25.8,2.6,10)
print("Before Sortingn",t1)
L1=list(t1)
L1.sort()
t1=tuple(L1)
print("Before Sortingn",t1)
Output:
Before Sorting
(95.5, 25.8, 2.6, 10)
After Sorting
(2.6, 10, 25.8, 95.5)
 A tuple assignment can be used in for loop to traverse a list of tuples
Example:
Write a program to traverse tuples from a list:
>>>Students=[(1,"Aishwarya"),(2,"Mohanahari"),(3,"Dhivya")]
>>> for roll_no,name in students:
print(roll_no,name)
1 Aishwarya
2 Mohanahari
3 Dhivya
 Zip() is an inbuilt function in python.
 It takes items in sequence from a number of collections to make a list of tuples,
where each tuple contains one item from each collection.
 If the sequences are not of the same length then the result of zip() has the
length of the shorter sequence
Example:
>>> Items=['Laptop','Desktop','Mobile']
>>> Cost=[45000,35000,15000]
>>> Cost_of_items=tuple((list(zip(Items,Cost))))
>>> print(Cost_of_items)
(('Laptop', 45000), ('Desktop', 35000), ('Mobile', 15000))
 The * operator is used within zip function.
 The * operator unpacks a sequence into positional arguments.
>>> items_cost=(('Laptop', 45000), ('Desktop', 35000), ('Mobile', 15000))
>>> product,price=zip(*items_cost)
>>> print(product)
('Laptop', 'Desktop', 'Mobile')
>>> print(price)
(45000, 35000, 15000)
DICTIONARY
 Python dictionary is an collection of items.
 A dictionary has a key: value pair as elements
 Dictionaries are optimized to retrieve values when the key is known.
 Dictionaries are mutable
 Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
 An item has a key and the corresponding value expressed as a pair, key: value.
 values can be of any data type and can repeat,
 keys must be of immutable type (string, number or tuple with immutable elements) and must
be unique.
#empty dictionary
>>>D1={}
# all elements
>>> marks={'Sivapriya':90,‘Shruthi':95}
>>> print(marks)
{'Sivapriya': 90,‘Shruthi': 95}
# one element at a time
>>> m={}
>>> m['Mitun']=85
>>> print(m)
{'Mitun': 85}
#empty dictionary
>>>D1=dict()
#keys must be string
>>> m=dict(Sivapriya=90,Shruthi=95)
>>> print(m)
{'Sivapriya': 90, 'Shruthi': 95}
#another method (suitable for runtime input)
>>> marks=dict(((1,90),(2,95)))
>>> print(marks)
{1: 90, 2: 95}
Method 1- Method 2-using dict()
 Dictionary uses keys to access elements.
 Key can be used either inside square brackets or with the get()
method.
 When key is used with in square bracket, raises an Key error, if the
key is not found
 get() returns None, if the key is not found.
marks={'Sivapriya':90,'Shruthi':95}
>>> marks['Shruthi']
95
>>> marks['Mitun']
KeyError: 'Mitun'
>>> marks.get('Sivapriya')
90
>>> marks.get('Mitun')
>>>
 Dictionary are mutable.We can add new items or change the value of
existing items using assignment operator.
 If the key is already present, value gets updated, else a new key: value
pair is added to the dictionary.
Dictionary_name[key]=value
#change value
>>> marks['Shruthi']=100
>>> print(marks)
{'Sivapriya': 90, 'Shruthi': 100}
#To add new item
>>> marks['Mitun']=80
>>> print(marks)
{'Sivapriya': 90, 'Shruthi': 100, 'Mitun': 80}
my_dict = {'name':'Jack', 'age': 26}
# change value
my_dict['age'] = 27
print(my_dict)
{'name': 'Jack‘,'age': 27}
# add item
my_dict['address'] = ‘Coimbatore'
print(my_dict)
{'name': 'Jack‘, 'age': 27 ,'address':
‘Coimbatore'}
Example-2
#update() –updates elements from the another
dictionary object or from an iterable of key/value
pairs.
marks.update([('Mohamed',85),('Siddharth',70)])
>>> print(marks)
{'Sivapriya': 90, 'Shruthi': 100, 'Mitun': 80,
'Mohamed': 85, 'Siddharth': 70}
pop()-method removes as item with
the provided key and returns the
value.
marks={'Sivapriya':90, 'Shruthi': 100,
'Mitun': 80}
>>> marks.pop('Mitun')
80
>>> print(marks)
{'Sivapriya':90, 'Shruthi': 100}
popitem() can be used to remove and
return an arbitrary item (key, value) from
the dictionary(python 3-inserted order)
>>> marks.popitem()
('Shruthi', 100)
>>> print(marks)
{'Sivapriya':90}
Clear()-All the items can be
removed at once
>>> marks.clear()
>>> print(marks)
{}
del- keyword to remove individual items
or the entire dictionary itself.
marks={'Sivapriya':90, 'Shruthi': 100,
'Mitun': 80}
>>> del marks['Shruthi']
>>> print(marks)
{'Sivapriya':90, 'Mitun': 80}
>>> del marks
>>> print(marks)
NameError: name 'marks' is not defined
 A dictionary with in dictionary
#Creating nested dictionary
>>> players={"virat Kohli":{"ODI":7212,"Test":3245},"Sachin":{"ODI":18426,"Test":15921}}
>>> print(players)
{'virat Kohli': {'ODI': 7212, 'Test': 3245}, 'Sachin': {'ODI': 18426, 'Test': 15921}}
#Accessing
>>> print(players['virat Kohli'])
{'ODI': 7212, 'Test': 3245}
>>> print(players['Sachin']['Test'])
15921
Operation Example Output
Membership Test
Test if a key is in a
dictionary or not
Test for value
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(5 in squares)
print(25 in squares.values())
True
True
Iterating Through
a Dictionary
Iterate though each
key in a dictionary.
for i in squares:
print(i,end=‘,’)
for n,s in squares.items():
print(n,s)
1,3,5,7,9,
1 1
3 9
5 25
7 49
9 81
Nested
dictionary
for name,score in players.items():
print(name)
print(score)
for name,score in players.items():
print(name)
print("ODI=",score['ODI'])
print("Test=",score['Test'])
virat Kohli
{'ODI': 7212, 'Test': 3245}
Sachin
{'ODI': 18426, 'Test': 15921}
virat Kohli
ODI= 7212
Test= 3245
Sachin
ODI= 18426
Test= 15921
Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq, v)
Return a new dictionary with keys from seq and value equal
to v (defaults to None).
get(key,d) Return the value of key. If key doesnot exit, return d(defaults to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
pop(key,d)
Remove the item with key and return its value or d if key is not found.
If d is not provided and key is not found, raises KeyError.
popitem()
Remove and return an last item (key, value)(version 3.7). Return
arbitrary item in older python versions. Raises KeyError if it is empty.
setdefault(key,d)
If key is in the dictionary, return its value. If not, insert key with a value
of d and return d (defaults to None).
update([other])
Update the dictionary with the key/value pairs from other, overwriting
existing keys.
values() Return a new view of the dictionary's values
marks = {}.fromkeys(['Math','English','Science'], 0)
print(marks)
for item in marks.items():
print(item)
for key in marks.keys():
print(item)
for value in marks.values():
print(item)
Output:
{'English': 0, 'Science': 0, 'Math': 0}
('English', 0)
('Science',0)
('Math', 0)
English
Science
Math
0
0
0
Function Description
all()
Return True if all keys of the dictionary are true (or if the
dictionary is empty).
any()
Return True if any key of the dictionary is true. If the
dictionary is empty, return False.
len() Return the length (the number of items) in the dictionary.
sorted() Return a new sorted list of keys in the dictionary.
 Write a program to create phone directory using dictionary. Retrieve the contacts
and phone numbers as pair and also individually.
phonebook={"person1":878988949,"person2":986599566}
print("List of Contacts:")
for contacts in phonebook.items():
print(contacts)
print("Contact Names:")
for name in phonebook.keys():
print(name)
print("Mobile Numbers:")
for phone_no in phonebook.values():
print(phone_no)
Output:
List of Contacts:
('person1',
878988949)
('person2',
986599566)
Contact Names:
person1
person2
Mobile Numbers:
878988949
986599566
 Dictionary can be used to represent polynomial
 It is used to map a power to a coefficient
Representation of Polynomial
Consider, P(x) = 4x3 + 3x2+5x+1
Dictionary representation: P = {3:4,2:3,1:5,0:1}
Consider , P(x) = 9x7 + 3x4+5x
Dictionary representation: P = {7:9,4:3,1:5}
List can also be used to represent polynomial. But we have to fill in all zero
coefficients too since index must match power. Ex: 9x7 + 3x4+5x can be
represented in list as P=[9,0,0,3,0,0,5,0].
So dictionary can be used to represent polynomial, where we can specify only
non zero coefficients.
Write a Program to evaluate the polynomial P(x) = 4x3 + 3x2+5x+1
Program:
x=int(input("Enter x value"))
P={3:4,2:3,1:5,0:1}
result=0
for k,v in P.items():
result=result+(v*pow(x,k))
print(“The value of Polynomial P(x) = 4x^3+3x^2+5x+1 is:”, result)
Output:
Enter x value
2
The value of Polynomial P(x) = 4x^3+3x^2+5x+1 is : 55

More Related Content

What's hot

Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in python
Sangita Panchal
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
Krishna Nanda
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
narmadhakin
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
Sharath Ankrajegowda
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
NehaSpillai1
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
ammarbrohi
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
VedaGayathri1
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
channa basava
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
Ravinder Kamboj
 
LIST IN PYTHON
LIST IN PYTHONLIST IN PYTHON
LIST IN PYTHON
vikram mahendra
 
Python list
Python listPython list
Python list
ArchanaBhumkar
 
Strings in python
Strings in pythonStrings in python
Strings in python
Prabhakaran V M
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
Amisha Narsingani
 
html-table
html-tablehtml-table
html-table
Dhirendra Chauhan
 
Python for loop
Python for loopPython for loop
Python for loop
Aishwarya Deshmukh
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
vikram mahendra
 

What's hot (20)

Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
List and Dictionary in python
List and Dictionary in pythonList and Dictionary in python
List and Dictionary in python
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
List , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in pythonList , tuples, dictionaries and regular expressions in python
List , tuples, dictionaries and regular expressions in python
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
LIST IN PYTHON
LIST IN PYTHONLIST IN PYTHON
LIST IN PYTHON
 
Python list
Python listPython list
Python list
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
html-table
html-tablehtml-table
html-table
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Python for loop
Python for loopPython for loop
Python for loop
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
 

Similar to Python tuples and Dictionary

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
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
Aswini Dharmaraj
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
omprakashmeena48
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
Panimalar Engineering College
 
Tuple.py
Tuple.pyTuple.py
Tuple.py
nuripatidar
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
Inzamam Baig
 
Python programming Sequence Datatypes -Tuples
Python programming Sequence Datatypes -TuplesPython programming Sequence Datatypes -Tuples
Python programming Sequence Datatypes -Tuples
BushraKm2
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
AnirudhaGaikwad4
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
Knoldus Inc.
 
Slicing in Python - What is It?
Slicing in Python - What is It?Slicing in Python - What is It?
Slicing in Python - What is It?
💾 Radek Fabisiak
 
beginners_python_cheat_sheet -python cheat sheet description
beginners_python_cheat_sheet -python cheat sheet descriptionbeginners_python_cheat_sheet -python cheat sheet description
beginners_python_cheat_sheet -python cheat sheet description
NaveenVarma Chintalapati
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
Yagna15
 
Python Tuple.pdf
Python Tuple.pdfPython Tuple.pdf
Python Tuple.pdf
T PRIYA
 
Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptxTuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
AyushTripathi998357
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202
Mahmoud Samir Fayed
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
Asst.prof M.Gokilavani
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210
Mahmoud Samir Fayed
 

Similar to Python tuples and Dictionary (20)

Pytho_tuples
Pytho_tuplesPytho_tuples
Pytho_tuples
 
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
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
Python for Beginners(v3)
Python for Beginners(v3)Python for Beginners(v3)
Python for Beginners(v3)
 
Tuple.py
Tuple.pyTuple.py
Tuple.py
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
Python programming Sequence Datatypes -Tuples
Python programming Sequence Datatypes -TuplesPython programming Sequence Datatypes -Tuples
Python programming Sequence Datatypes -Tuples
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Collections In Scala
Collections In ScalaCollections In Scala
Collections In Scala
 
Slicing in Python - What is It?
Slicing in Python - What is It?Slicing in Python - What is It?
Slicing in Python - What is It?
 
Pytho lists
Pytho listsPytho lists
Pytho lists
 
beginners_python_cheat_sheet -python cheat sheet description
beginners_python_cheat_sheet -python cheat sheet descriptionbeginners_python_cheat_sheet -python cheat sheet description
beginners_python_cheat_sheet -python cheat sheet description
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
Python Tuple.pdf
Python Tuple.pdfPython Tuple.pdf
Python Tuple.pdf
 
Tuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptxTuples-and-Dictionaries.pptx
Tuples-and-Dictionaries.pptx
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210
 

Recently uploaded

A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
nooriasukmaningtyas
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
drwaing
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
Divyam548318
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
Rahul
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
awadeshbabu
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
dxobcob
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 

Recently uploaded (20)

A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...A review on techniques and modelling methodologies used for checking electrom...
A review on techniques and modelling methodologies used for checking electrom...
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
digital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdfdigital fundamental by Thomas L.floydl.pdf
digital fundamental by Thomas L.floydl.pdf
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
bank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdfbank management system in java and mysql report1.pdf
bank management system in java and mysql report1.pdf
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
 
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
一比一原版(Otago毕业证)奥塔哥大学毕业证成绩单如何办理
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 

Python tuples and Dictionary

  • 3. Tuples are sequences, just like lists. A tuple contains a sequence of items of any data type The difference between the tuple and list is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed. Elements in the tuples are fixed Once it is created, we cannot add or remove elements Hence tuples are immutable
  • 4. Since, tuples are quite similar to lists, both of them are used in similar situations as well. However, there are certain advantages of implementing a tuple over a list. Tuples that contain immutable elements can be used as key for a dictionary.With list, this is not possible. If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-protected.
  • 5.  A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma.  The parentheses are optional but is a good practice to write it.  A tuple can have any number of items and they may be of different types (integer, float, list, string etc.). # empty tule T1=() # tuples having of integers T2 = (1, 2, 3) # tuple with mixed datatypes T3 = (1, "Hello", 3.4) # nested tuple T4 = (“welcome", (8, 4, 6)) Method -1 Method-2 # empty tuple T1= tuple() # tuple function with string as arguments my_list = tuple(“welcome”) • Creating a tuple with one element is a bit tricky. • Single element should be followed by comma >>> T1=(4) >>> type(T1) <class 'int'> >>> T1=(4,) >>> type(T1) <class 'tuple'>
  • 6. we can access the elements of a tuple using index & slice operator Indexing  We can use the index operator [] to access an item in a tuple where the index starts from 0. >>> t1=(10,20,30) >>> print(t1[2]) 30 >>> print(t1[-3]) 10 Slicing  We can access a range of items in a tuple by using the slicing operator - colon ":“ >>>print(t1[0:2:1]) (10, 20) #nested tuple >>> t1=(10,20,(15,25)) >>> print(t1[2][0]) 15
  • 7.  Unlike lists, tuples are immutable.  This means that elements of a tuple cannot be changed once it has been assigned. >>> t1=(5,10,15,[50,90]) >>> t1[0]=100 TypeError: 'tuple' object does not support item assignment But, if the element is itself a mutable datatype like list, its nested items can be changed. >>> t1[3][1]=100 >>> print(t1) (5, 10, 15, [50, 100])
  • 8.  Tuples are immutable which means you cannot add elements to tuple  Removing individual tuple elements is not possible.  To explicitly remove an entire tuple, just use the del statement >>> del t1 >>> t1 NameError: name 't1' is not defined
  • 9. Description Python Expression Results Concatenation (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Repetition ('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Membership 3 in (1, 2, 3) True Iteration for x in (1, 2, 3): print x, 1 2 3
  • 10. Method Description count(x) Return the number of items that is equal to x index(x) Return index of first item that is equal to x
  • 11. Function Description all() Return True if all elements of the tuple are true (or if the tuple is empty). any() Return True if any element of the tuple is true. If the tuple is empty, return False. len() Return the length (the number of items) in the tuple. max() Return the largest item in the tuple. min() Return the smallest item in the tuple sorted() Take elements in the tuple and return a new sorted list (does not sort the tuple itself). sum() Return the sum of all elements in the tuple.
  • 12. Method 1-using sorted() function >>>t1=(95.5,25.8,2.6,10) >>> t2=tuple(sorted(t1)) >>>print(t2) (2.6, 10, 25.8, 95.5) Method 2 Tuple does not contain sort() method. so to sort tuple, it can be converted into list, then sort the list, again convert the sorted list into tuple Program: t1=(95.5,25.8,2.6,10) print("Before Sortingn",t1) L1=list(t1) L1.sort() t1=tuple(L1) print("Before Sortingn",t1) Output: Before Sorting (95.5, 25.8, 2.6, 10) After Sorting (2.6, 10, 25.8, 95.5)
  • 13.  A tuple assignment can be used in for loop to traverse a list of tuples Example: Write a program to traverse tuples from a list: >>>Students=[(1,"Aishwarya"),(2,"Mohanahari"),(3,"Dhivya")] >>> for roll_no,name in students: print(roll_no,name) 1 Aishwarya 2 Mohanahari 3 Dhivya
  • 14.  Zip() is an inbuilt function in python.  It takes items in sequence from a number of collections to make a list of tuples, where each tuple contains one item from each collection.  If the sequences are not of the same length then the result of zip() has the length of the shorter sequence Example: >>> Items=['Laptop','Desktop','Mobile'] >>> Cost=[45000,35000,15000] >>> Cost_of_items=tuple((list(zip(Items,Cost)))) >>> print(Cost_of_items) (('Laptop', 45000), ('Desktop', 35000), ('Mobile', 15000))
  • 15.  The * operator is used within zip function.  The * operator unpacks a sequence into positional arguments. >>> items_cost=(('Laptop', 45000), ('Desktop', 35000), ('Mobile', 15000)) >>> product,price=zip(*items_cost) >>> print(product) ('Laptop', 'Desktop', 'Mobile') >>> print(price) (45000, 35000, 15000)
  • 17.  Python dictionary is an collection of items.  A dictionary has a key: value pair as elements  Dictionaries are optimized to retrieve values when the key is known.  Dictionaries are mutable
  • 18.  Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.  An item has a key and the corresponding value expressed as a pair, key: value.  values can be of any data type and can repeat,  keys must be of immutable type (string, number or tuple with immutable elements) and must be unique. #empty dictionary >>>D1={} # all elements >>> marks={'Sivapriya':90,‘Shruthi':95} >>> print(marks) {'Sivapriya': 90,‘Shruthi': 95} # one element at a time >>> m={} >>> m['Mitun']=85 >>> print(m) {'Mitun': 85} #empty dictionary >>>D1=dict() #keys must be string >>> m=dict(Sivapriya=90,Shruthi=95) >>> print(m) {'Sivapriya': 90, 'Shruthi': 95} #another method (suitable for runtime input) >>> marks=dict(((1,90),(2,95))) >>> print(marks) {1: 90, 2: 95} Method 1- Method 2-using dict()
  • 19.  Dictionary uses keys to access elements.  Key can be used either inside square brackets or with the get() method.  When key is used with in square bracket, raises an Key error, if the key is not found  get() returns None, if the key is not found. marks={'Sivapriya':90,'Shruthi':95} >>> marks['Shruthi'] 95 >>> marks['Mitun'] KeyError: 'Mitun' >>> marks.get('Sivapriya') 90 >>> marks.get('Mitun') >>>
  • 20.  Dictionary are mutable.We can add new items or change the value of existing items using assignment operator.  If the key is already present, value gets updated, else a new key: value pair is added to the dictionary. Dictionary_name[key]=value #change value >>> marks['Shruthi']=100 >>> print(marks) {'Sivapriya': 90, 'Shruthi': 100} #To add new item >>> marks['Mitun']=80 >>> print(marks) {'Sivapriya': 90, 'Shruthi': 100, 'Mitun': 80} my_dict = {'name':'Jack', 'age': 26} # change value my_dict['age'] = 27 print(my_dict) {'name': 'Jack‘,'age': 27} # add item my_dict['address'] = ‘Coimbatore' print(my_dict) {'name': 'Jack‘, 'age': 27 ,'address': ‘Coimbatore'} Example-2 #update() –updates elements from the another dictionary object or from an iterable of key/value pairs. marks.update([('Mohamed',85),('Siddharth',70)]) >>> print(marks) {'Sivapriya': 90, 'Shruthi': 100, 'Mitun': 80, 'Mohamed': 85, 'Siddharth': 70}
  • 21. pop()-method removes as item with the provided key and returns the value. marks={'Sivapriya':90, 'Shruthi': 100, 'Mitun': 80} >>> marks.pop('Mitun') 80 >>> print(marks) {'Sivapriya':90, 'Shruthi': 100} popitem() can be used to remove and return an arbitrary item (key, value) from the dictionary(python 3-inserted order) >>> marks.popitem() ('Shruthi', 100) >>> print(marks) {'Sivapriya':90} Clear()-All the items can be removed at once >>> marks.clear() >>> print(marks) {} del- keyword to remove individual items or the entire dictionary itself. marks={'Sivapriya':90, 'Shruthi': 100, 'Mitun': 80} >>> del marks['Shruthi'] >>> print(marks) {'Sivapriya':90, 'Mitun': 80} >>> del marks >>> print(marks) NameError: name 'marks' is not defined
  • 22.  A dictionary with in dictionary #Creating nested dictionary >>> players={"virat Kohli":{"ODI":7212,"Test":3245},"Sachin":{"ODI":18426,"Test":15921}} >>> print(players) {'virat Kohli': {'ODI': 7212, 'Test': 3245}, 'Sachin': {'ODI': 18426, 'Test': 15921}} #Accessing >>> print(players['virat Kohli']) {'ODI': 7212, 'Test': 3245} >>> print(players['Sachin']['Test']) 15921
  • 23. Operation Example Output Membership Test Test if a key is in a dictionary or not Test for value squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} print(5 in squares) print(25 in squares.values()) True True Iterating Through a Dictionary Iterate though each key in a dictionary. for i in squares: print(i,end=‘,’) for n,s in squares.items(): print(n,s) 1,3,5,7,9, 1 1 3 9 5 25 7 49 9 81 Nested dictionary for name,score in players.items(): print(name) print(score) for name,score in players.items(): print(name) print("ODI=",score['ODI']) print("Test=",score['Test']) virat Kohli {'ODI': 7212, 'Test': 3245} Sachin {'ODI': 18426, 'Test': 15921} virat Kohli ODI= 7212 Test= 3245 Sachin ODI= 18426 Test= 15921
  • 24. Method Description clear() Remove all items form the dictionary. copy() Return a shallow copy of the dictionary. fromkeys(seq, v) Return a new dictionary with keys from seq and value equal to v (defaults to None). get(key,d) Return the value of key. If key doesnot exit, return d(defaults to None). items() Return a new view of the dictionary's items (key, value). keys() Return a new view of the dictionary's keys. pop(key,d) Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError. popitem() Remove and return an last item (key, value)(version 3.7). Return arbitrary item in older python versions. Raises KeyError if it is empty. setdefault(key,d) If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None). update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. values() Return a new view of the dictionary's values
  • 25. marks = {}.fromkeys(['Math','English','Science'], 0) print(marks) for item in marks.items(): print(item) for key in marks.keys(): print(item) for value in marks.values(): print(item) Output: {'English': 0, 'Science': 0, 'Math': 0} ('English', 0) ('Science',0) ('Math', 0) English Science Math 0 0 0
  • 26. Function Description all() Return True if all keys of the dictionary are true (or if the dictionary is empty). any() Return True if any key of the dictionary is true. If the dictionary is empty, return False. len() Return the length (the number of items) in the dictionary. sorted() Return a new sorted list of keys in the dictionary.
  • 27.  Write a program to create phone directory using dictionary. Retrieve the contacts and phone numbers as pair and also individually. phonebook={"person1":878988949,"person2":986599566} print("List of Contacts:") for contacts in phonebook.items(): print(contacts) print("Contact Names:") for name in phonebook.keys(): print(name) print("Mobile Numbers:") for phone_no in phonebook.values(): print(phone_no) Output: List of Contacts: ('person1', 878988949) ('person2', 986599566) Contact Names: person1 person2 Mobile Numbers: 878988949 986599566
  • 28.  Dictionary can be used to represent polynomial  It is used to map a power to a coefficient Representation of Polynomial Consider, P(x) = 4x3 + 3x2+5x+1 Dictionary representation: P = {3:4,2:3,1:5,0:1} Consider , P(x) = 9x7 + 3x4+5x Dictionary representation: P = {7:9,4:3,1:5} List can also be used to represent polynomial. But we have to fill in all zero coefficients too since index must match power. Ex: 9x7 + 3x4+5x can be represented in list as P=[9,0,0,3,0,0,5,0]. So dictionary can be used to represent polynomial, where we can specify only non zero coefficients.
  • 29. Write a Program to evaluate the polynomial P(x) = 4x3 + 3x2+5x+1 Program: x=int(input("Enter x value")) P={3:4,2:3,1:5,0:1} result=0 for k,v in P.items(): result=result+(v*pow(x,k)) print(“The value of Polynomial P(x) = 4x^3+3x^2+5x+1 is:”, result) Output: Enter x value 2 The value of Polynomial P(x) = 4x^3+3x^2+5x+1 is : 55