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}

Python Lecture 11

  • 1.
    Creative Commons License Thiswork 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 isa 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 atuple with a single element, you have to include the final comma: >>> t1 = ('a',) >>> type(t1) <type 'tuple'>
  • 5.
    Without the commaPython 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 operatorindexes an element: >>> t = ('a', 'b', 'c', 'd', 'e') >>> print(t[0]) 'a' >>> print(t[1:3]) ('b', 'c')
  • 9.
    If you tryto 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 modifythe 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 startsby 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 = 'butsoft 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 Dictionarieshave 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 dictionaryto 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 withdictionaries 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')]
  • 24.
  • 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 isan 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 cannothave 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 anddictionary while creating empty set a = {} print(type(a)) a = set() print(type(a))
  • 30.
    Sets are unorderedtherefore indexing has no meaning my_set = {1, 3} my_set[0] TypeError: 'set' object is not subscriptable
  • 31.
  • 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}
  • 34.
  • 35.
  • 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 isan unordered data type, there is no way of determining which item will be popped. It is completely arbitrary
  • 39.
  • 40.
    IN Operator my_set =set("apple") print('a' in my_set) True print('p' not in my_set) False
  • 41.
    Iterating over aset >>> 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.
  • 44.
    Union is performedusing | 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}
  • 46.
  • 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}
  • 49.
  • 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}
  • 52.
  • 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