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}

More Related Content

PPTX
Python Lecture 10
PPTX
Python Lecture 8
PDF
Python Workshop Part 2. LUG Maniapl
PDF
List , tuples, dictionaries and regular expressions in python
PDF
Python programming : List and tuples
Python Lecture 10
Python Lecture 8
Python Workshop Part 2. LUG Maniapl
List , tuples, dictionaries and regular expressions in python
Python programming : List and tuples

What's hot (20)

PPTX
Dictionaries in python
PDF
1. python
PDF
Python Regular Expressions
PDF
Python Variable Types, List, Tuple, Dictionary
PDF
Python :variable types
PDF
Arrays in python
PDF
Datatypes in python
PDF
Python programming : Strings
PPTX
List in Python
PPTX
Dictionaries and Sets
PPTX
Basic data structures in python
PPTX
Data Structures in Python
PPTX
An Introduction to Tuple List Dictionary in Python
PDF
Python list
PPTX
Chapter 14 strings
PDF
Python dictionary : past, present, future
PPTX
Python Datatypes by SujithKumar
PPTX
Python dictionary
PPTX
Datastructures in python
PPTX
Python Modules and Libraries
Dictionaries in python
1. python
Python Regular Expressions
Python Variable Types, List, Tuple, Dictionary
Python :variable types
Arrays in python
Datatypes in python
Python programming : Strings
List in Python
Dictionaries and Sets
Basic data structures in python
Data Structures in Python
An Introduction to Tuple List Dictionary in Python
Python list
Chapter 14 strings
Python dictionary : past, present, future
Python Datatypes by SujithKumar
Python dictionary
Datastructures in python
Python Modules and Libraries
Ad

Similar to Python Lecture 11 (20)

PPT
Tuples, sets and dictionaries-Programming in Python
PPTX
Brixton Library Technology Initiative
PPTX
Python data structures
PPTX
Python data structures
PPTX
Python data structures
PPTX
Python data structures
PPTX
Python data structures
PPTX
Python data structures
PPTX
Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx
PPTX
Python data structures
PPTX
Tuples-and-Dictionaries.pptx
PPTX
Python introduction data structures lists etc
PPT
Tuples, sets angsdfgsfdgdfgfdgd dictionaries 2.ppt
PPTX
Chapter 3-Data structure in python programming.pptx
PPTX
UNIT-3 python and data structure alo.pptx
PPTX
Learn python - for beginners - part-2
PDF
Python tuples and Dictionary
PDF
ESIT135 Problem Solving Using Python Notes of Unit-3
DOC
Revision Tour 1 and 2 complete.doc
PPTX
cover every basics of python with this..
Tuples, sets and dictionaries-Programming in Python
Brixton Library Technology Initiative
Python data structures
Python data structures
Python data structures
Python data structures
Python data structures
Python data structures
Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx
Python data structures
Tuples-and-Dictionaries.pptx
Python introduction data structures lists etc
Tuples, sets angsdfgsfdgdfgfdgd dictionaries 2.ppt
Chapter 3-Data structure in python programming.pptx
UNIT-3 python and data structure alo.pptx
Learn python - for beginners - part-2
Python tuples and Dictionary
ESIT135 Problem Solving Using Python Notes of Unit-3
Revision Tour 1 and 2 complete.doc
cover every basics of python with this..
Ad

More from Inzamam Baig (11)

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

Recently uploaded (20)

PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Supply Chain Operations Speaking Notes -ICLT Program
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Renaissance Architecture: A Journey from Faith to Humanism
human mycosis Human fungal infections are called human mycosis..pptx
Basic Mud Logging Guide for educational purpose
Microbial diseases, their pathogenesis and prophylaxis
Final Presentation General Medicine 03-08-2024.pptx
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
O5-L3 Freight Transport Ops (International) V1.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
TR - Agricultural Crops Production NC III.pdf
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
VCE English Exam - Section C Student Revision Booklet
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx

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