Python Workshop Part 2. LUG Maniapl
-
Upload
ankur-shrivastava -
Category
Technology
-
view
941 -
download
1
description
Transcript of Python Workshop Part 2. LUG Maniapl
![Page 1: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/1.jpg)
Advanced Data Structures
● Lists● Tuples● Sets● Dictionaries
![Page 2: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/2.jpg)
Introduction to lists
Python knows a number of compound datatypes, used to group together other values. Themost versatile is the list, which can be written asa list of comma-separated values (items)between square brackets. List items need notall have the same type.
![Page 3: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/3.jpg)
>>> a = [100,200,300,400,500]>>> a[100,200,300,400,500]
Can be accessed with index values like arraysin C/C++/Java.
>>> a[0]100
Access the 2nd element from the end of the list>>> a[-2]400
![Page 4: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/4.jpg)
Slicing: Extract values from the list within agiven index range.
For eg. from the 2nd element of the given list tothe last but one element.
>>> a[1:-1][200, 300, 400]
![Page 5: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/5.jpg)
Some special cases
listobject[:x]– If x is a positive value, then x number of entries
from the beginning of the list would be sliced >>a[:3] [100, 200, 300]
– If x is a negative value, for eg -2, then all the entries from the list except the last 2 would be sliced
>>> a[:-2] [100, 200, 300]
![Page 6: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/6.jpg)
Some special cases(contd...)
listobject[x:]– If x is positive, all the entries except for the first x
entries would be sliced >>> a[2:] [300, 400, 500]
– If x is negative, for eg -2, then 2 entries from the end of the list would be sliced
>>> a[-2:] [400, 500]
![Page 7: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/7.jpg)
Assignment to slices is also possible, and thiscan even change the size of the list or clear itentirely
>>> a[0:2] = [1, 12]>>> a[1, 12, 300, 400, 500]
Removing a slice>>> a[0:2] = []>>> a[300, 400, 500]
![Page 8: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/8.jpg)
Assignment to slices (special case)
You can empty the whole list with
>>> a[:] = []>>> a[]
![Page 9: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/9.jpg)
Nesting lists
>>> q=[2,3]>>> p=[1,q,4]>>> p[1, [2, 3], 4]
>>> p[1][2, 3]
![Page 10: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/10.jpg)
Methods of the list data type
● list.append(x)Add an item to the end of the list
● list.extend(L)Extend the list by appending all the items in thegiven list
![Page 11: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/11.jpg)
● list.insert(i, x)Insert an item at a given position. The first argumentis the index of the element before which to insert, soa.insert(0, x) inserts at the front of the list, anda.insert(len(a), x) is equivalent to a.append(x)
● list.remove(x)Remove the first item from the list whose value is x.It is an error if there is no such item.
● list.index(x)Return the index in the list of the first item whosevalue is x. It is an error if there is no such item.
![Page 12: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/12.jpg)
● list.pop([i])Remove the item at the given position in the list, andreturn it. If no index is specified, a.pop() removesand returns the last item in the list
● list.count(x)Return the number of times x appears in the list.
● list.sort()● list.reverse()
![Page 13: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/13.jpg)
● Another way to remove entries from a list is the use of the del statement
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]>>> del a[0]>>> a[1, 66.25, 333, 333, 1234.5]>>> del a[2:4]>>> a[1, 66.25, 1234.5]>>> del a[:]>>> a[]
![Page 14: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/14.jpg)
TuplesA tuple consists of a number of valuesseparated by commas, for instance:
>>> t = 12345, 54321, 'hello!'>>> t[0]12345>>> t(12345, 54321, 'hello!')>>>u = t, (1, 2, 3, 4, 5) # Tuples may be nested
>>> u((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
![Page 15: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/15.jpg)
● Construct a single element tuple
>>> singleton = 'hello', # note trailing comma>>> singleton('hello',)
The statement t = 12345,54321,'hello!'is an example of tuple packing
![Page 16: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/16.jpg)
●Sequence unpacking
Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence
>>> x, y, z = t
![Page 17: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/17.jpg)
Sets
A set is an unordered collection with noduplicate elements. Set objects also supportmathematical operations like union,intersection, difference, and symmetricdifference.
![Page 18: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/18.jpg)
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> fruit = set(basket) >>> fruitset(['orange', 'pear', 'apple', 'banana'])
# fast membership testing
>>> 'orange' in fruit True>>> 'crabgrass' in fruitFalse
![Page 19: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/19.jpg)
Set operations on unique letters from two words
>>> a = set('abracadabra')>>> b = set('alacazam')
# unique letters in a>>> a set(['a', 'r', 'b', 'c', 'd'])
# letters in a but not in b>>> a - b set(['r', 'd', 'b'])
![Page 20: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/20.jpg)
# letters in either a or b>>> a | b set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
# letters in both a and b>>> a & b set(['a', 'c'])
# letters in a or b but not both>>> a ^ b set(['r', 'd', 'b', 'm', 'z', 'l'])
![Page 21: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/21.jpg)
Dictionaries
Unordered set of key: value pairs, with therequirement that the keys are unique (withinone dictionary)
>>> tel = {'jack': 4098, 'sape': 4139}>>> tel['guido'] = 4127>>> tel{'sape': 4139, 'guido': 4127, 'jack': 4098}
![Page 22: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/22.jpg)
The keys() method of the dictionary data typereturns a list of the keys.
>>> tel.keys()['sape', 'jack', 'guido']
Both keys and values can either be strings ornumbers.
![Page 23: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/23.jpg)
● Build a dictionary from key-value pairs stored as tuples
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
Note the dict() constructor
![Page 24: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/24.jpg)
Looping techniques
Use the iteritems() method to loop throughdictionaries
>>> knights = {’gallahad’: ’the pure’, ’robin’: ’the brave’}
>>> for k, v in knights.iteritems():... print k, v...gallahad the purerobin the brave
![Page 25: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/25.jpg)
Looping over two sequences at the same time
Use the zip() method
>>> a = ['foo','bar']>>> b = [42, 0]>>> for i,j in zip(a,b):... print "%s:%d" % (i,j)... foo:42bar:0
![Page 26: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/26.jpg)
File objects● Quick introduction to file handling
open() returns a file object, and is most commonlyused with two arguments: ‘open(filename, mode)’
>>> f = open('temp.txt','w')>>> f<open file 'temp.txt', mode 'w' at0xb7d4c5c0>
![Page 27: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/27.jpg)
● 'r' The file must already exist, and it is opened inread-only mode.
● 'w' The file is opened in write-only mode. The file istruncated and overwritten if it already exists, orcreated if it does not exist.
![Page 28: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/28.jpg)
● 'a' The file is opened in write-only mode. The file iskept intact if it already exists, and the data youwrite is appended to what's already in the file.The file is created if it does not exist.
● 'r+' The file must already exist and is opened forboth reading and writing, so all methods of f canbe called .
![Page 29: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/29.jpg)
● 'w+' The file is opened for both reading and writing,so all methods of f can be called. The file istruncated and overwritten if it already exists, orcreated if it does not exist.
● 'a+' The file is opened for both reading and writing,so all methods of f can be called. The file is keptintact if it already exists, and the data you writeis appended to what's already in the file. The
fileis created if it does not exist.
![Page 30: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/30.jpg)
● Reading from a file object
f.read(size)
The size is an optional argument, which whenspecified reads that many bytes at most. Ifnothing is specified, it reads the contents of thewhole file and returns it as a string.
![Page 31: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/31.jpg)
f.readline()
Reads a line from the file, returns it as a stringand moves on to the next line.
f.readlines()
This returns a list of all the lines in the file. Canbe used to loop through the contents of a file.For eg
>>>for line in f.readlines():... print line...
![Page 32: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/32.jpg)
● Writing to a file
f.write(string)
It's simple!
● Closing the file object
f.close()
Close the file and free up system resourcesbeing used by the file object.
![Page 33: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/33.jpg)
A few important string functions
● s.split()Splits a string consisting of words seperated bywhitespaces and returns a list of the words.
● s.rstrip()Remove whitespaces from the leading end orthe right side
● s.lstrip()
![Page 34: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/34.jpg)
Exceptions
Errors detected during execution are calledexceptions and are not unconditionally fatal.
![Page 35: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/35.jpg)
Handling exceptions
Overall structure....
try: #code that may cause runtime #errorexcept [errortype]: #handle the error[else:] #do something if no error raised[finally:] #irrespective of error being #raised or not do something
![Page 36: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/36.jpg)
>>> while True:... try:... x = int(raw_input("enter anumber: "))... break... except ValueError:... print "Oops!"...
![Page 37: Python Workshop Part 2. LUG Maniapl](https://reader034.fdocuments.in/reader034/viewer/2022050804/5406de288d7f72d8088b4803/html5/thumbnails/37.jpg)
● Raising exceptions
>>> raise NameError, ’HiThere’Traceback (most recent call last): File "<stdin>", line 1, in ?NameError: HiThere
Try this: Accept two numbers, raise aValueError when division by 0 is attempted andhandle it too