🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Unit 3 460..ppt

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Datatype: List The items stored in the list are separated with a comma (,) and enclosed within square brackets []. List is mutable in nature. The list can contain data of different types. Syntax: list1 = [1, "hi", "Python", 2.5] A LIST IS A KIND OF COLLECTION  A collection allows us to put...

Datatype: List The items stored in the list are separated with a comma (,) and enclosed within square brackets []. List is mutable in nature. The list can contain data of different types. Syntax: list1 = [1, "hi", "Python", 2.5] A LIST IS A KIND OF COLLECTION  A collection allows us to put many values in a single “variable”  A collection is nice because we can carry all many values around in one convenient package. friends = [ 'Joseph', 'Glenn', 'Sally' ] carryon = [ 'socks', 'shirt', 'perfume' ]  Most of our variables have one value in them - when we put a new value in the variable - the old value is over written $ python Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin >>> x = 2 >>> x = 4 >>> print x 4 LIST CONSTANTS  List constants are surrounded by >>> print [1, 24, 76] square brakets and the elements in the list are separated by commas. [1, 24, 76]  A list element can be any Python >>> print ['red', 'yellow', 'blue'] object - even another list ['red', 'yellow', 'blue']  A list can be empty >>> print ['red', 24, 98.6] ['red', 24, 98.599999999999994 >>> print [ 1, [5, 6], 7] [1, [5, 6], 7] >>> print [] [] WE ALREADY USE LISTS! 5 4 for i in [5, 4, 3, 2, 1] : 3 print i 2 print 'Blastoff!' 1 Blastoff! LISTS AND DEFINITE LOOPS - BEST PALS friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends : print 'Happy New Year:', friend print 'Done!' Output: Happy New Year: JosephHappy New Year: GlennHappy New Year: SallyD LOOKING INSIDE LISTS  Just like strings, we can get at any single element in a list using an index specified in square brackets >>> friends = [ 'Joseph', 'Glenn', 'Sally Joseph Glenn Sally >>> print friends Glenn 0 1 2 >>> LISTS ARE >>> fruit = 'Banana’ >>> fruit = 'b’ MUTABLE Traceback TypeError: 'str' object does  Strings are "immutable" - we cannot change the contents of a not string - we must make a new support item assignment string to make any change >>> x = fruit.lower()  Lists are "mutable" - we can change an element of a list using >>> print x the index operator banana >>> lotto = [2, 14, 26, 41, 63] >>> print lotto[2, 14, 26, 41, 63] >>> lotto = 28 >>> print lotto [2, 14, 28, 41, 63]  The len() function takes a list as a parameter and returns the number of elements in the list >>> greet = 'Hello Bob’  Actually len() tells us the number of >>> print len(greet) elements of any set or sequence (i.e. such as a string...) 9 >>> x = [ 1, 2, 'joe', 99] >>> print len(x) 4 >>> USING THE RANGE FUNCTION  The range function returns a list of numbers that range from zero to >>> print range(4) one less than the parameter [0, 1, 2, 3]  We can construct an index loop >>> friends = ['Joseph', 'Glenn', 'Sall using for and an integer iterator >>> print len(friends) 3 >>> print range(len(friends)) [0, 1, 2] >>> A TALE OF TWO LOOPS... >>> friends = ['Joseph', 'Glenn', 'Sall >>> print len(friends) friends = ['Joseph', 'Glenn', 'Sally'] 3 >>> print range(len(friends)) for friend in friends : [0, 1, 2] print 'Happy New Year:', friend >>> for i in range(len(friends)) : friend = friends[i] Happy New Year: Joseph print 'Happy New Year:', friend Happy New Year: Glenn Happy New Year: Sally  We can create a new list by adding two exsiting lists together >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> print c [1, 2, 3, 4, 5, 6] >>> print a [1, 2, 3] >>> t = [9, 41, 12, 3, 74, 15] >>> t[1:3] [41,12] Remember: Just like >>> t[:4] in strings, the second [9, 41, 12, 3] number is "up to but >>> t[3:] not including" [3, 74, 15] >>> t[:] [9, 41, 12, 3, 74, 15] LIST METHODS >>> x = list() >>> type(x) >>> dir(x)['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>>  We can create an empty list and then add elements using the append method >>> stuff = list()  The list stays in order and >>> stuff.append('book') new elements are added at the end of the list >>> stuff.append(99) >>> print stuff ['book', 99] >>> stuff.append('cookie') >>> print stuff ['book', 99, 'cookie'] IS SOMETHING IN A LIST?  Python provides two operators that let you check if an item is in a list >>> some = [1, 9, 21, 10, 16]  These are logical operators >>> 9 in some that return True or False True  They do not modify the list >>> 15 in some False >>> 20 not in some True >>>  A list can hold many items and keeps those items in the order until we do something to change the order >>> friends = [ 'Joseph', 'Glenn', 'Sal  A list can be sorted (i.e. change >>> its friends.sort() order) >>> print friends ['Glenn', 'Joseph', 'Sally']  The sort method (unlike in strings) means "sort yourself" >>> print friends Joseph>>>  There are a number of functions built into Python >>> nums = [3, 41, 12, 9, 74, 15] that take lists as parameters >>> print len(nums)  Remember the loops we 6 built? These are much simpler >>> print max(nums) 74>>> print min(nums) 3 >>> print sum(nums) 154 >>> print sum(nums)/len(nums) 25 Enter a number: 3 total = 0 count = 0 Enter a number: 9 while True : Enter a number: 5 inp = raw_input('Enter a number: ') if inp == 'done' : break Enter a number: done value = float(inp) Average: total = total + value count = count + 1 5.66666666667 average = total / count print 'Average:', average numlist = list() while True : inp = raw_input('Enter a number: ') if inp == 'done' : break value = float(inp) numlist.append(value) average = sum(numlist) / len(numlist) print 'Average:', average STRINGS AND LISTS >>> abc = 'With three words’ >>> print stuff >>> stuff = abc.split() ['With', 'three', 'words'] >>> print stuff >>> for w in stuff : ['With', 'three', 'words']... print w >>> print len(stuff)... 3 With >>> print stuff Three With Words >>> Split breaks a string into parts produces a list of strings. We think of these as words. We can access a particular word or loop through all the words. >>> line = 'A lot of spaces’ >>> etc = line.split() >>> print etc['A', 'lot', 'of', 'spaces'] >>> >>> line = 'first;second;third’ >>> thing = line.split() >>> print thing['first;second;third'] >>> print len(thing) 1 >>> thing = line.split(';') >>> print thing['first', 'second', 'third'] >>> print len(thing) 3 When you do not specify a delimiter, >>> multiple spaces are treated like “one” delimiter. You can specify what delimiter character to use in the splitting. LIST SUMMARY Accessing List By using the slicing operator List[1:6:2]={2, list_varible(start:stop:s 4,6} tep) FUNCTIONS/METHODS IN LIST: len() function in python: This function when applied to a list will return the length of the elements in it. count() method in Python: This method returns the number of occurrences of a specific item in the list append() method in Python: Using this method we can add elements to the list. The items or elements will be added at the end of the list. FUNCTIONS/METHODS IN LIST: insert() method in Python: We can add elements to the list object by using the insert() method. The insert() method takes two arguments as input: one is the index and the other is the element. It will add the elements to the list at the specified index. extend() method in Python: Using this method the items in one list can be added to the other. FUNCTIONS/METHODS IN LIST: remove() method in Python: We can use this method to remove specific items from the list. If the item exists multiple times, then only the first occurrence will be removed. If the specified item not present in list, then we will get ValueError. pop() method in Python: This method takes an index as an argument and removes and returns the element present at the given index. If no index is given, then the last item is removed and returned by default. FUNCTIONS/METHODS IN LIST: reverse() method in python: This method reverses the order of list elements. sort() method in Python: In a list by default insertion order is preserved. If we want to sort the elements of the list according to the default natural sorting order then we should go for the sort() method. For numbers, the default natural sorting order is ascending order. For strings, the default natural sorting order is alphabetical order. To use the sort() method, the list should contain only homogeneous elements otherwise, we will get TypeError. Tuple: Like lists, tuples also contain the collection of the items of different data types. The items of the tuple are separated with a comma (,) and enclosed in parentheses (). A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple. Syntax: mytuple=(1, "hi", "Python", 2) TUPLES ARE LIKE LISTS  Tuples are another kind of sequence that function much like a list - they have elements which are indexed starting at 0 >>> x = ('Glenn', 'Sally', 'Joseph') >>> for iter in y: >>> print xJoseph... print iter >>> y = ( 1, 9, 2 )... >>> print y 1 (1, 9, 2) 9 >>> print max(y) 2 9 >>>  Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string >>> y = 'ABC’ >>> z = (5, 4, 3)>>> >>> x = [9, 8, 7] >>> y = 'D’ z = 0 >>> x = 6 Traceback:'str' Traceback:'tuple' >>> print x[9, 8, 6] object does object does >>> not support item not support item Assignment Assignment >>> >>> >>> x = (3, 2, 1) >>> x.sort() Traceback:AttributeError: 'tuple' object has no attribute 'sort’ >>> x.append(5) Traceback:AttributeError: 'tuple' object has no attribute 'append’ >>> x.reverse() Traceback:AttributeError: 'tuple' object has no attribute 'reverse’ >>> A TALE OF TWO SEQUENCES >>> l = list() >>> dir(l)[ 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> t = tuple() >>> dir(t) ['count', 'index'] TUPLES ARE MORE EFFICIENT  Since Python does not have to build tuple structures to be modifiable, they are simpler and more efficient in terms of memory use and performance than lists  So in our program when we are making "temporary variables" we prefer tuples over lists. TUPLES AND ASSIGNMENT  We can also put a tuple on the left hand side of an assignment statement  We can even omit the parenthesis >>> (x, y) = (4, 'fred') >>> print y Fred >>> (a, b) = (99, 98) >>> print a 99 TUPLES AND DICTIONARIES >>> d = dict()  The items() >>> d['csev'] = 2 >>> d['cwen'] = 4 method in >>> for (k,v) in d.items(): dictionaries returns... print k, v a list of (key,... value) tuples csev 2 cwen 4 >>> tups = d.items() >>> print tups [('csev', 2), ('cwen', 4)]  The comparison operators work with tuples and other sequences If the first item is equal, Python goes on to the next element, and so on, until it finds elements that differ. >>> (0, 1, 2) < (5, 1, 2) True >>> (0, 1, 2000000) < (0, 3, 4) True >>> ( 'Jones', 'Sally' ) < ('Jones', 'Sam') True >>> ( 'Jones', 'Sally') > ('Adams', 'Sam') True USING >>> d = {'a':10, 'b':1, 'c':22} SORTED() >>> d.items() [('a', 10), ('c', 22), ('b', 1)] >>> t = sorted(d.items()) We can sort using >>> t the built-in function [('a', 10), ('b', 1), ('c', 22)] sorted that takes a sequence as a >>> for k, v in sorted(d.items()): parameter and... print k, v... returns a sorted a 10 sequence b1 c 22 SORT BY VALUES INSTEAD OF KEY  If we could >>> c = {'a':10, 'b':1, 'c':22} construct a list >>> tmp = list() of tuples of the >>> for k, v in c.items() : form (value,... tmp.append( (v, k) ) key) we could... sort by value >>> print tmp [(10, 'a'), (22, 'c'), (1, 'b')]  We do this with >>> tmp.sort(reverse=True) a for loop that >>> print tmp creates a list of [(22, 'c'), (10, 'a'), (1, 'b')] tuples fhand = open('romeo.txt') counts = dict() for line in fhand: words = line.split() for word in words: counts[word] = counts.get(word, 0 ) + 1 lst = list() for key, val in counts.items(): lst.append( (val, key) ) lst.sort(reverse=True) for val, key in lst[:10] : print key, val >>> c = {'a':10, 'b':1, 'c':22} >>> print sorted( [ (v,k) for k,v in c.items() ] ) [(1, 'b'), (10, 'a'), (22, 'c')] List comprehension creates a dynamic list. In this case, we make a list of reversed tuples and then sort it. SUMMARY Accessing Tuple By using the slicing operator max(): This function returns the large element from the tuple. min(): This function returns the minimum element from the tuple. len(): This function returns the number of elements in a tuple. tuple(): Creating a tuple from a list , string, set, dictionary etc.. count() method: This method returns the number of occurrences of a specified element in the tuple. index() method: This method returns the index of the first occurrence of a specified element in the tuple.

Use Quizgecko on...
Browser
Browser