SlideShare a Scribd company logo
1 of 54
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}

More Related Content

What's hot (20)

Dictionaries in python
Dictionaries in pythonDictionaries in python
Dictionaries in python
 
1. python
1. python1. python
1. python
 
Python Regular Expressions
Python Regular ExpressionsPython Regular Expressions
Python Regular Expressions
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
List in Python
List in PythonList in Python
List in Python
 
Dictionaries and Sets
Dictionaries and SetsDictionaries and Sets
Dictionaries and Sets
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
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
 
Python list
Python listPython list
Python list
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Python dictionary : past, present, future
Python dictionary: past, present, futurePython dictionary: past, present, future
Python dictionary : past, present, future
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Python Modules and Libraries
Python Modules and LibrariesPython Modules and Libraries
Python Modules and Libraries
 

Similar to Python Lecture 11

Lists.pptx
Lists.pptxLists.pptx
Lists.pptxYagna15
 
PRESENTATION ON TUPLES.pptx
PRESENTATION ON TUPLES.pptxPRESENTATION ON TUPLES.pptx
PRESENTATION ON TUPLES.pptxrohan899711
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfomprakashmeena48
 
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.docSrikrishnaVundavalli
 
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.pdfAsst.prof M.Gokilavani
 
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_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
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.pdfTimothy McBush Hiele
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdfHimoZZZ
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadiesAlicia Pérez
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdfNehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdfNehaSpillai1
 

Similar to Python Lecture 11 (20)

Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Python Workshop
Python  Workshop Python  Workshop
Python Workshop
 
PRESENTATION ON TUPLES.pptx
PRESENTATION ON TUPLES.pptxPRESENTATION ON TUPLES.pptx
PRESENTATION ON TUPLES.pptx
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
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
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
Python 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!
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 
Tuples in Python
Tuples in PythonTuples in Python
Tuples in Python
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Array
ArrayArray
Array
 
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
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadies
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 

More from Inzamam Baig

More from Inzamam Baig (11)

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

Recently uploaded

COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Pooja Bhuva
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 

Recently uploaded (20)

COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 

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

  1. Tuples are also comparable and hashable so we can sort lists of them and use tuples as key values in Python dictionaries