SlideShare a Scribd company logo
Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.
BS GIS Instructor: Inzamam Baig
Lecture 11
Fundamentals of Programming
Tuples
A tuple is a sequence of values much like a list
The values stored in a tuple can be any type, and they are
indexed by integers
Tuples are immutable
Tuples are also comparable and hashable
Defining a tuple
>>> t = 'a', 'b', 'c', 'd', ‘e’
>>> t = ('a', 'b', 'c', 'd', 'e')
To create a tuple with a single element, you have to include the
final comma:
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>
Without the comma Python treats ('a') as an expression with a
string in parentheses that evaluates to a string:
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
>>> t = tuple()
>>> print(t)
()
>>> t = tuple('lupins’)
>>> print(t)
('l', 'u', 'p', 'i', 'n', 's')
The bracket operator indexes an element:
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print(t[0])
'a'
>>> print(t[1:3])
('b', 'c')
If you try to modify one of the elements of the tuple, you get an
error:
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
You can’t modify the elements of a tuple, but you can replace one
tuple with another:
>>> t = ('A',) + t[1:]
>>> print(t)
('A', 'b', 'c', 'd', 'e')
Comparing tuples
Python starts by comparing the first element from each sequence
If they are equal, it goes on to the next element, and so on, until it
finds elements that differ
Comparing tuples
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
txt = 'but soft what light in yonder window breaks'
words = txt.split()
t = list()
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = list()
for length, word in t:
res.append(word)
print(res)
Tuple assignment
>>> m = [ 'have', 'fun' ]
>>> x, y = m
>>> x
'have'
>>> y
'fun'
>>>
Tuple assignment
>>> m = [ 'have', 'fun' ]
>>> x = m[0]
>>> y = m[1]
>>> x
'have'
>>> y
'fun'
Tuple assignment
>>> m = [ 'have', 'fun' ]
>>> (x, y) = m
>>> x
'have'
>>> y
'fun'
Tuple unpacking
>>> a, b = b, a
Both sides of this statement are tuples, but the left side is a tuple
of variables; the right side is a tuple of expressions
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
>>> 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
DICTIONARIES AND TUPLES
Dictionaries have a method called items that returns a list of tuples,
where each tuple is a key-value pair
>>> d = {'a':10, 'b':1, 'c':22}
>>> t = list(d.items())
>>> print(t)
[('b', 1), ('a', 10), ('c', 22)]
the items are in no particular order
Converting a dictionary to a list of tuples is a way for us to
output the contents of a dictionary sorted by key
>>> d = {'a':10, 'b':1, 'c':22}
>>> t = list(d.items())
>>> t
[('b', 1), ('a', 10), ('c', 22)]
>>> t.sort()
>>> t
[('a', 10), ('b', 1), ('c', 22)]
Multiple assignment with dictionaries
for key, val in list(d.items()):
print(val, key)
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
>>> d = {'a':10, 'b':1, 'c':22}
>>> l = list()
>>> for key, val in d.items() :
... l.append( (val, key) )
...
>>> l
[(10, 'a'), (22, 'c'), (1, 'b')]
>>> l.sort(reverse=True)
>>> l
[(22, 'c'), (10, 'a'), (1, 'b')]
The most common words
import string
fhand = open('romeo-full.txt')
counts = dict()
for line in fhand:
line = line.translate(str.maketrans('', '', string.punctuation))
line = line.lower()
words = line.split()
for word in words:
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)
Sets
A set is an unordered collection of items
Every set element is unique (no duplicates) and must be
immutable (cannot be changed)
Sets are mutable
Sets can also be used to perform mathematical set operations
like union, intersection, symmetric difference
Defining a Set
s1 = set()
my_set = {1, 2, 3}
print(my_set)
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
Duplicate Values
set cannot have duplicates
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
{1, 2, 3, 4}
my_set = set([1, 2, 3, 2])
print(my_set)
{1, 2, 3}
set cannot have mutable items
my_set = {1, 2, [3, 4]}
Distinguish set and dictionary while creating empty set
a = {}
print(type(a))
a = set()
print(type(a))
Sets are unordered therefore indexing has no meaning
my_set = {1, 3}
my_set[0]
TypeError: 'set' object is not subscriptable
Add
my_set.add(2)
print(my_set)
{1, 2, 3}
Update
my_set.update([2, 3, 4])
print(my_set)
{1, 2, 3, 4}
my_set.update([4, 5], {1, 6, 8})
print(my_set)
{1, 2, 3, 4, 5, 6, 8}
Removing Elements
my_set = {1, 3, 4, 5, 6}
my_set.discard(4)
print(my_set)
{1, 3, 5, 6}
Removing Elements
my_set.remove(6)
print(my_set)
{1, 3, 5}
discard an element
my_set.discard(2)
print(my_set)
{1, 3, 5}
my_set.remove(2)
KeyError: 2
discard vs remove
discard() function leaves a set unchanged if the element is not
present in the set
On the other hand, the remove() function will raise an error in
such a condition (if element is not present in the set)
Removing Elements
my_set = set("HelloWorld")
print(my_set)
pop random element
print(my_set.pop())
print(my_set)
Since set is an unordered data type, there is no way of
determining which item will be popped. It is completely arbitrary
my_set.clear()
print(my_set)
IN Operator
my_set = set("apple")
print('a' in my_set)
True
print('p' not in my_set)
False
Iterating over a set
>>> for letter in set("apple"):
... print(letter)
...
a
p
e
l
Set Operations
>>> A = {1, 2, 3, 4, 5}
>>> B = {4, 5, 6, 7, 8}
Union
Union is performed using | operator
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A | B)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> A.union(B)
{1, 2, 3, 4, 5, 6, 7, 8}
>>> B.union(A)
{1, 2, 3, 4, 5, 6, 7, 8}
Intersection
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A & B)
{4, 5}
>>> A.intersection(B)
{4, 5}
>>> B.intersection(A)
{4, 5}
Difference
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A - B)
{1, 2, 3}
>>> A.difference(B)
{1, 2, 3}
>>> B.difference(A)
{8, 6, 7}
Symmetric Difference
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A ^ B)
{1, 2, 3, 6, 7, 8}
>>> A.symmetric_difference(B)
{1, 2, 3, 6, 7, 8}
>>> B.symmetric_difference(A)
{1, 2, 3, 6, 7, 8}
Ad

More Related Content

What's hot (20)

Dictionaries in python
Dictionaries in pythonDictionaries in python
Dictionaries in python
JayanthiNeelampalli
 
1. python
1. python1. python
1. python
PRASHANT OJHA
 
Python Regular Expressions
Python Regular ExpressionsPython Regular Expressions
Python Regular Expressions
BMS Institute of Technology and Management
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
S.M. Salaquzzaman
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
List in Python
List in PythonList in Python
List in Python
Siddique Ibrahim
 
Dictionaries and Sets
Dictionaries and SetsDictionaries and Sets
Dictionaries and Sets
Munazza-Mah-Jabeen
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
Python list
Python listPython list
Python list
Mohammed Sikander
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
Praveen M Jigajinni
 
Python dictionary : past, present, future
Python dictionary: past, present, futurePython dictionary: past, present, future
Python dictionary : past, present, future
delimitry
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
Mohammed Sikander
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Python Modules and Libraries
Python Modules and LibrariesPython Modules and Libraries
Python Modules and Libraries
Venugopalavarma Raja
 

Similar to Python Lecture 11 (20)

Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
Yagna15
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
Krishna Nanda
 
Python programming Sequence Datatypes -Tuples
Python programming Sequence Datatypes -TuplesPython programming Sequence Datatypes -Tuples
Python programming Sequence Datatypes -Tuples
BushraKm2
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
Assem CHELLI
 
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
 
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
 
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
Guru Nanak Technical Institutions
 
Python list tuple dictionary .pptx
Python list tuple dictionary       .pptxPython list tuple dictionary       .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
Paige Bailey
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
TanTran598844
 
Python_for_data_science_cheatsheet EMERSON EDUARDO RODRIGUES.pdf
Python_for_data_science_cheatsheet EMERSON EDUARDO RODRIGUES.pdfPython_for_data_science_cheatsheet EMERSON EDUARDO RODRIGUES.pdf
Python_for_data_science_cheatsheet EMERSON EDUARDO RODRIGUES.pdf
EMERSON EDUARDO RODRIGUES
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
DPS Ranipur Haridwar UK
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Array
ArrayArray
Array
Malainine Zaid
 
R Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdfR Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdf
Timothy McBush Hiele
 
Chapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptxChapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
HimoZZZ
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
Rakotoarison Louis Frederick
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
Yagna15
 
Python programming Sequence Datatypes -Tuples
Python programming Sequence Datatypes -TuplesPython programming Sequence Datatypes -Tuples
Python programming Sequence Datatypes -Tuples
BushraKm2
 
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
 
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
 
Python list tuple dictionary .pptx
Python list tuple dictionary       .pptxPython list tuple dictionary       .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
Paige Bailey
 
Python_for_data_science_cheatsheet EMERSON EDUARDO RODRIGUES.pdf
Python_for_data_science_cheatsheet EMERSON EDUARDO RODRIGUES.pdfPython_for_data_science_cheatsheet EMERSON EDUARDO RODRIGUES.pdf
Python_for_data_science_cheatsheet EMERSON EDUARDO RODRIGUES.pdf
EMERSON EDUARDO RODRIGUES
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
sagar414433
 
R Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdfR Cheat Sheet for Data Analysts and Statisticians.pdf
R Cheat Sheet for Data Analysts and Statisticians.pdf
Timothy McBush Hiele
 
Chapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptxChapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
HimoZZZ
 
Ad

More from Inzamam Baig (11)

Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
Inzamam Baig
 
Python Lecture 12
Python Lecture 12Python Lecture 12
Python Lecture 12
Inzamam Baig
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
Inzamam Baig
 
Python Lecture 7
Python Lecture 7Python Lecture 7
Python Lecture 7
Inzamam Baig
 
Python Lecture 6
Python Lecture 6Python Lecture 6
Python Lecture 6
Inzamam Baig
 
Python Lecture 5
Python Lecture 5Python Lecture 5
Python Lecture 5
Inzamam Baig
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
Inzamam Baig
 
Python Lecture 3
Python Lecture 3Python Lecture 3
Python Lecture 3
Inzamam Baig
 
Python Lecture 2
Python Lecture 2Python Lecture 2
Python Lecture 2
Inzamam Baig
 
Python Lecture 1
Python Lecture 1Python Lecture 1
Python Lecture 1
Inzamam Baig
 
Python Lecture 0
Python Lecture 0Python Lecture 0
Python Lecture 0
Inzamam Baig
 
Ad

Recently uploaded (20)

114P_English.pdf114P_English.pdf114P_English.pdf
114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf
114P_English.pdf114P_English.pdf114P_English.pdf
paulinelee52
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
ITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQ
SONU HEETSON
 
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdfIPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
IPL QUIZ | THE QUIZ CLUB OF PSGCAS | 2025.pdf
Quiz Club of PSG College of Arts & Science
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Cyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top QuestionsCyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top Questions
SONU HEETSON
 
How to Manage Manual Reordering Rule in Odoo 18 Inventory
How to Manage Manual Reordering Rule in Odoo 18 InventoryHow to Manage Manual Reordering Rule in Odoo 18 Inventory
How to Manage Manual Reordering Rule in Odoo 18 Inventory
Celine George
 
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdfGENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
GENERAL QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 4 MARCH 2025 .pdf
Quiz Club of PSG College of Arts & Science
 
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptxUnit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Mayuri Chavan
 
Rebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter worldRebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter world
Ned Potter
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
businessweekghana
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-14-2025 .pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-14-2025  .pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-14-2025  .pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-14-2025 .pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale OrderHow to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale Order
Celine George
 
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERSIMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
rajaselviazhagiri1
 
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit..."Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
AlionaBujoreanu
 
Aerospace Engineering Homework Help Guide – Expert Support for Academic Success
Aerospace Engineering Homework Help Guide – Expert Support for Academic SuccessAerospace Engineering Homework Help Guide – Expert Support for Academic Success
Aerospace Engineering Homework Help Guide – Expert Support for Academic Success
online college homework help
 
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdfAntepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Dr H.K. Cheema
 
How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18
Celine George
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
114P_English.pdf114P_English.pdf114P_English.pdf
114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf114P_English.pdf
114P_English.pdf114P_English.pdf114P_English.pdf
paulinelee52
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
ITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQITI COPA Question Paper PDF 2017 Theory MCQ
ITI COPA Question Paper PDF 2017 Theory MCQ
SONU HEETSON
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
Cyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top QuestionsCyber security COPA ITI MCQ Top Questions
Cyber security COPA ITI MCQ Top Questions
SONU HEETSON
 
How to Manage Manual Reordering Rule in Odoo 18 Inventory
How to Manage Manual Reordering Rule in Odoo 18 InventoryHow to Manage Manual Reordering Rule in Odoo 18 Inventory
How to Manage Manual Reordering Rule in Odoo 18 Inventory
Celine George
 
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptxUnit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Unit 5 ACUTE, SUBACUTE,CHRONIC TOXICITY.pptx
Mayuri Chavan
 
Rebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter worldRebuilding the library community in a post-Twitter world
Rebuilding the library community in a post-Twitter world
Ned Potter
 
Pope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptxPope Leo XIV, the first Pope from North America.pptx
Pope Leo XIV, the first Pope from North America.pptx
Martin M Flynn
 
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
UPSA JUDGEMENT.pdfCopyright Infringement: High Court Rules against UPSA: A Wa...
businessweekghana
 
How to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale OrderHow to Change Sequence Number in Odoo 18 Sale Order
How to Change Sequence Number in Odoo 18 Sale Order
Celine George
 
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERSIMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
IMPACT_OF_SOCIAL-MEDIA- AMONG- TEENAGERS
rajaselviazhagiri1
 
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit..."Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
"Bridging Cultures Through Holiday Cards: 39 Students Celebrate Global Tradit...
AlionaBujoreanu
 
Aerospace Engineering Homework Help Guide – Expert Support for Academic Success
Aerospace Engineering Homework Help Guide – Expert Support for Academic SuccessAerospace Engineering Homework Help Guide – Expert Support for Academic Success
Aerospace Engineering Homework Help Guide – Expert Support for Academic Success
online college homework help
 
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdfAntepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Antepartum fetal surveillance---Dr. H.K.Cheema pdf.pdf
Dr H.K. Cheema
 
How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18How to Use Upgrade Code Command in Odoo 18
How to Use Upgrade Code Command in Odoo 18
Celine George
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 

Python Lecture 11

  • 1. Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License. BS GIS Instructor: Inzamam Baig Lecture 11 Fundamentals of Programming
  • 2. Tuples A tuple is a sequence of values much like a list The values stored in a tuple can be any type, and they are indexed by integers Tuples are immutable Tuples are also comparable and hashable
  • 3. Defining a tuple >>> t = 'a', 'b', 'c', 'd', ‘e’ >>> t = ('a', 'b', 'c', 'd', 'e')
  • 4. To create a tuple with a single element, you have to include the final comma: >>> t1 = ('a',) >>> type(t1) <type 'tuple'>
  • 5. Without the comma Python treats ('a') as an expression with a string in parentheses that evaluates to a string: >>> t2 = ('a') >>> type(t2) <type 'str'>
  • 6. >>> t = tuple() >>> print(t) ()
  • 7. >>> t = tuple('lupins’) >>> print(t) ('l', 'u', 'p', 'i', 'n', 's')
  • 8. The bracket operator indexes an element: >>> t = ('a', 'b', 'c', 'd', 'e') >>> print(t[0]) 'a' >>> print(t[1:3]) ('b', 'c')
  • 9. If you try to modify one of the elements of the tuple, you get an error: >>> t[0] = 'A' TypeError: object doesn't support item assignment
  • 10. You can’t modify the elements of a tuple, but you can replace one tuple with another: >>> t = ('A',) + t[1:] >>> print(t) ('A', 'b', 'c', 'd', 'e')
  • 11. Comparing tuples Python starts by comparing the first element from each sequence If they are equal, it goes on to the next element, and so on, until it finds elements that differ
  • 12. Comparing tuples >>> (0, 1, 2) < (0, 3, 4) True >>> (0, 1, 2000000) < (0, 3, 4) True
  • 13. txt = 'but soft what light in yonder window breaks' words = txt.split() t = list() for word in words: t.append((len(word), word)) t.sort(reverse=True) res = list() for length, word in t: res.append(word) print(res)
  • 14. Tuple assignment >>> m = [ 'have', 'fun' ] >>> x, y = m >>> x 'have' >>> y 'fun' >>>
  • 15. Tuple assignment >>> m = [ 'have', 'fun' ] >>> x = m[0] >>> y = m[1] >>> x 'have' >>> y 'fun'
  • 16. Tuple assignment >>> m = [ 'have', 'fun' ] >>> (x, y) = m >>> x 'have' >>> y 'fun'
  • 17. Tuple unpacking >>> a, b = b, a Both sides of this statement are tuples, but the left side is a tuple of variables; the right side is a tuple of expressions
  • 18. >>> a, b = 1, 2, 3 ValueError: too many values to unpack
  • 19. >>> 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
  • 20. DICTIONARIES AND TUPLES Dictionaries have a method called items that returns a list of tuples, where each tuple is a key-value pair >>> d = {'a':10, 'b':1, 'c':22} >>> t = list(d.items()) >>> print(t) [('b', 1), ('a', 10), ('c', 22)] the items are in no particular order
  • 21. Converting a dictionary to a list of tuples is a way for us to output the contents of a dictionary sorted by key >>> d = {'a':10, 'b':1, 'c':22} >>> t = list(d.items()) >>> t [('b', 1), ('a', 10), ('c', 22)] >>> t.sort() >>> t [('a', 10), ('b', 1), ('c', 22)]
  • 22. Multiple assignment with dictionaries for key, val in list(d.items()): print(val, key) 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
  • 23. >>> d = {'a':10, 'b':1, 'c':22} >>> l = list() >>> for key, val in d.items() : ... l.append( (val, key) ) ... >>> l [(10, 'a'), (22, 'c'), (1, 'b')] >>> l.sort(reverse=True) >>> l [(22, 'c'), (10, 'a'), (1, 'b')]
  • 25. import string fhand = open('romeo-full.txt') counts = dict() for line in fhand: line = line.translate(str.maketrans('', '', string.punctuation)) line = line.lower() words = line.split() for word in words: 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)
  • 26. Sets A set is an unordered collection of items Every set element is unique (no duplicates) and must be immutable (cannot be changed) Sets are mutable Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference
  • 27. Defining a Set s1 = set() my_set = {1, 2, 3} print(my_set) my_set = {1.0, "Hello", (1, 2, 3)} print(my_set)
  • 28. Duplicate Values set cannot have duplicates my_set = {1, 2, 3, 4, 3, 2} print(my_set) {1, 2, 3, 4} my_set = set([1, 2, 3, 2]) print(my_set) {1, 2, 3} set cannot have mutable items my_set = {1, 2, [3, 4]}
  • 29. Distinguish set and dictionary while creating empty set a = {} print(type(a)) a = set() print(type(a))
  • 30. Sets are unordered therefore indexing has no meaning my_set = {1, 3} my_set[0] TypeError: 'set' object is not subscriptable
  • 32. Update my_set.update([2, 3, 4]) print(my_set) {1, 2, 3, 4} my_set.update([4, 5], {1, 6, 8}) print(my_set) {1, 2, 3, 4, 5, 6, 8}
  • 33. Removing Elements my_set = {1, 3, 4, 5, 6} my_set.discard(4) print(my_set) {1, 3, 5, 6}
  • 35. discard an element my_set.discard(2) print(my_set) {1, 3, 5} my_set.remove(2) KeyError: 2
  • 36. discard vs remove discard() function leaves a set unchanged if the element is not present in the set On the other hand, the remove() function will raise an error in such a condition (if element is not present in the set)
  • 37. Removing Elements my_set = set("HelloWorld") print(my_set) pop random element print(my_set.pop()) print(my_set)
  • 38. Since set is an unordered data type, there is no way of determining which item will be popped. It is completely arbitrary
  • 40. IN Operator my_set = set("apple") print('a' in my_set) True print('p' not in my_set) False
  • 41. Iterating over a set >>> for letter in set("apple"): ... print(letter) ... a p e l
  • 42. Set Operations >>> A = {1, 2, 3, 4, 5} >>> B = {4, 5, 6, 7, 8}
  • 43. Union
  • 44. Union is performed using | operator A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A | B) {1, 2, 3, 4, 5, 6, 7, 8}
  • 45. >>> A.union(B) {1, 2, 3, 4, 5, 6, 7, 8} >>> B.union(A) {1, 2, 3, 4, 5, 6, 7, 8}
  • 47. A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A & B) {4, 5}
  • 48. >>> A.intersection(B) {4, 5} >>> B.intersection(A) {4, 5}
  • 50. A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A - B) {1, 2, 3}
  • 51. >>> A.difference(B) {1, 2, 3} >>> B.difference(A) {8, 6, 7}
  • 53. A = {1, 2, 3, 4, 5} B = {4, 5, 6, 7, 8} print(A ^ B) {1, 2, 3, 6, 7, 8}
  • 54. >>> A.symmetric_difference(B) {1, 2, 3, 6, 7, 8} >>> B.symmetric_difference(A) {1, 2, 3, 6, 7, 8}

Editor's Notes

  • #3: Tuples are also comparable and hashable so we can sort lists of them and use tuples as key values in Python dictionaries
  翻译: