Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python Crash Course Containers 3 rd year Bachelors V1.0 dd 03-09-2013 Hour 3.

Similar presentations


Presentation on theme: "Python Crash Course Containers 3 rd year Bachelors V1.0 dd 03-09-2013 Hour 3."— Presentation transcript:

1 Python Crash Course Containers 3 rd year Bachelors V1.0 dd 03-09-2013 Hour 3

2 Introduction to language - containers Container data types in Python are types whose instances are capable of storing other objects. Some of the fundamental built-in container objects include: lists – the most popular container data type in python; can store any number of any objects. tuples – similar to list, yet once created are immutable, sets – can store only unique elements, bytes – immutable sequence of integers in the range 0 <= x < 256, bytearray – like bytes, but mutable, dictionary – also known as associative arrays. They contain mapping of keys into value, str – string, a sequence of unicode characters, range – a sequence of numbers — more precisely a list containing arithmetic progressions array.array – present in the array module. Similar to list, yet during the construction it is restricted to holding a specific data type,

3 Introduction to language - containers Data typeMutableOrderedLiteral exampleConstructor Sequence types listyes [1,2,3]list() tuplenoyes(1,2,3)tuple() strnoyes“text” / ‘text’str() rangenoyes–range() bytesnoyesb’abcde’ / b”abc”bytes() bytearrayyes –bytearray() array *yes –array.array() Set types setyesno{1,2,3}set() frozensetno –frozenset() Mapping types dictyesno{“key1″: “val”, “key2″: “val”}dict()

4 Containers – Mutable, Immutable, Hashable Containers in Python can be either mutable or immutable. The fact that a container object is immutable doesn’t always mean that the objects it holds are also immutable (e.g. an immutable tuple holding mutable lists). However, container objects are fully immutable only if the object itself, and the objects it contains are recursively immutable. Recursively immutable objects may be hashable. This is important as only hashable objects can be used in a mapping container object (see below) as keys. All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Examples of mutable containers include: list, set, dictionary, bytearray array Examples of immutable containers include: string, frozenset, tuple, bytes The main implication of the mutable/immutable distinction and hashability is that not all container object can store all other container objects, in particular: sets can store only hashable object (each object in set has to have a unique hash — sets do not store duplicate objects, as opposed to e.g. lists or tuples) dictionaries can have only hashable objects as keys

5 Containers – Ordered or Unordered Container object can store their content in either an ordered or unordered manner. Order, or lack of thereof, is unrelated to the mutability of objects. This means that both mutable and immutable objects can be either ordered or unordered. Examples of ordered containers include: list, string, tuple, bytes, bytearrays, array Examples of unordered containers include: dictionary, set, frozenset.

6 Containers - Lists Lists: >>> a = [1, 2, 4, 8, 16] # list of ints >>> c = [4, 'candles', 4.0, 'handles'] # can mix types >>> c[1] 'candles' >>> c[2] = 'knife' >>> c[-1] # negative indices count from end 'handles' >>> c[1:3] # slicing ['candles', 'knife'] >>> c[2:] # omitting defaults to start or end ['knife', 'handles'] >>> c[0:4:2] # variable stride (could just write c[::2]) [4, 'knife'] >>> a + c # concatenate [1, 2, 4, 8, 16, 4, 'candles', 'knife', 'handles'] >>> len(a) 5 Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type. The values stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the beginning of the list and working their way to end-1. The plus ( + ) sign is the list concatenation operator, and the asterisk ( * ) is the repetition operator.

7 Lists Methods SNFunction with Description 1cmp(list1, list2) cmp(list1, list2) Compares elements of both lists. 2len(list) len(list) Gives the total length of the list. 3max(list) max(list) Returns item from the list with max value. 4min(list) min(list) Returns item from the list with min value. 5list(seq) list(seq) Converts a tuple into list. SNMethods with Description 1list.append(obj) list.append(obj) Appends object obj to list 2list.count(obj) list.count(obj) Returns count of how many times obj occurs in list 3list.extend(seq) list.extend(seq) Appends the contents of seq to list 4list.index(obj) list.index(obj) Returns the lowest index in list that obj appears 5list.insert(index, obj) list.insert(index, obj) Inserts object obj into list at offset index 6list.pop(obj=list[-1]) list.pop(obj=list[-1]) Removes and returns last object or obj from list 7list.remove(obj) list.remove(obj) Removes object obj from list 8list.reverse() list.reverse() Reverses objects of list in place 9list.sort([func]) list.sort([func]) Sorts objects of list, use compare func if given

8 List operations list1 = ['physics', 'chemistry', 1997, 2000] print list1 del list1[2] print "After deleting value at index 2 : " print list1 L = [] #empty list L = list() A = B = [] # both names will point to the same list A = [] B = A # both names will point to the same list A = []; B = [] # independent lists for item in L: print item for index, item in enumerate(L): print index, item i = iter(L) item = i.next() # fetch first value item = i.next() # fetch second value stack = [] stack.append(object) # push object = stack.pop() # pop from end queue = [] queue.append(object) # push object = queue.pop(0) # pop from beginning

9 Containers - Tuples Tuples: >>> q = (1, 2, 4, 8, 16) # tuple of ints >>> r = (4, 'candles', 4.0, 'handles') # can mix types >>> s = ('lonely',) # singleton >>> t = () # empty >>> r[1] 'candles' >>> r[2] = 'knife' # cannot change tuples Traceback (most recent call last): File " ", line 1, in TypeError: 'tuple' object does not support item assignment >>> u = 3, 2, 1 # parentheses not necessary >>> v, w = 'this', 'that' >>> v 'this' >>> w 'that' A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ), and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

10 Use of tuples def func(x,y): # code to compute x and y return (x,y) (x,y) = func(1,2)

11 Tuple methods SNFunction with Description 1cmp(tuple1, tuple2) cmp(tuple1, tuple2) Compares elements of both tuples. 2len(tuple) len(tuple) Gives the total length of the tuple. 3max(tuple) max(tuple) Returns item from the tuple with max value. 4min(tuple) min(tuple) Returns item from the tuple with min value. 5tuple(seq) tuple(seq) Converts a list into tuple.

12 Containers - Dictionaries Dictionaries: >>> a = {'eyecolour': 'blue', 'height': 152.0, 42: 'the answer'} >>> a['age'] = 28 >>> a {42: 'the answer', 'age': 28, 'eyecolour': 'blue', 'height': 152.0} >>> del(a['height']) >>> a {42: 'the answer', 'age': 28, 'eyecolour': 'blue'} >>> b = {} >>> b['hello'] = 'Hi! ' >>> a.keys() [42, 'age’, 'eyecolour’] >>> a.values() ['the answer', 28, 'blue'] Python 's dictionaries are hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. Keys can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ( { } ) and values can be assigned and accessed using square braces ( [] ).

13 Dictionary use >>> colors = { "blue": (0x30,0x30,0xff), "green": (0x30,0xff,0x97),... "red": (0xff,0x30,0x97), "yellow": (0xff,0xff,0x30) } >>> for c in colors:... print c, colors[c] for key, value in someDictionary.items(): # process key and value print key, "=", value for value in someDictionary.values(): # process the value >>> i = { "two":2, "three":3, "quatro":4 } >>> del i["quatro"] >>> i {'two': 2, 'three': 3} >>> i = { "two":2, "three":3, "quatro":4 } >>> i.pop("quatro") 4 >>> i {'two': 2, 'three': 3}

14 Dictionary methods SNFunction with Description 1cmp(dict1, dict2) cmp(dict1, dict2) Compares elements of both dict. 2len(dict) len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the dictionary. 3str(dict) str(dict) Produces a printable string representation of a dictionary 4type(variable) type(variable) Returns the type of the passed variable. If passed variable is dictionary then it would return a dictionary type. SNMethods with Description 1dict.clear() dict.clear() Removes all elements of dictionary dict 2dict.copy() dict.copy() Returns a shallow copy of dictionary dict 2dict.fromkeys() dict.fromkeys() Create a new dictionary with keys from seq and values set to value. 3dict.get(key, default=None) dict.get(key, default=None) For key key, returns value or default if key not in dictionary 4dict.has_key(key) dict.has_key(key) Returns true if key in dictionary dict, false otherwise 5dict.items() dict.items() Returns a list of dict's (key, value) tuple pairs 6dict.keys() dict.keys() Returns list of dictionary dict's keys 7dict.setdefault(key, default=None) dict.setdefault(key, default=None) Similar to get(), but will set dict[key]=default if key is not already in dict 8dict.update(dict2) dict.update(dict2) Adds dictionary dict2's key-values pairs to dict 9dict.values() dict.values() Returns list of dictionary dict2's values

15 Type Conversions FunctionDescription int(x [,base])Converts x to an integer. base specifies the base if x is a string. long(x [,base] )Converts x to a long integer. base specifies the base if x is a string. float(x)Converts x to a floating-point number. complex(real [,imag])Creates a complex number. str(x)Converts object x to a string representation. repr(x)Converts object x to an expression string. eval(str)Evaluates a string and returns an object. tuple(s)Converts s to a tuple. list(s)Converts s to a list. set(s)Converts s to a set. dict(d)Creates a dictionary. d must be a sequence of (key,value) tuples. frozenset(s)Converts s to a frozen set. chr(x)Converts an integer to a character. unichr(x)Converts an integer to a Unicode character. ord(x)Converts a single character to its integer value. hex(x)Converts an integer to a hexadecimal string. oct(x)Converts an integer to an octal string.

16 Logical Operators End


Download ppt "Python Crash Course Containers 3 rd year Bachelors V1.0 dd 03-09-2013 Hour 3."

Similar presentations


Ads by Google