60 likes | 267 Views
Lists. Python lists. Always enclosed in square brackets. Can be any type and can be mixed types: [1,2,3] [“1”,2,”porcupine”] Lists can include other lists [1,2, [“include”,”me”] ,4] Or be empty []. List bits. The components of a list are called “elements”
E N D
Python lists • Always enclosed in square brackets. • Can be any type and can be mixed types: [1,2,3] [“1”,2,”porcupine”] • Lists can include other lists [1,2,[“include”,”me”],4] • Or be empty []
List bits • The components of a list are called “elements” League=[‘Man Utd’,’Chelsea’,’Liverpool’] League[1] League[1:] League[1:4] League[-1] League[:2] League[4] League[1:2] League[:-1]
Things to do with Lists • Find out if something is in a list if “Reading” in premiership: • Find out how many elements in a list print len(premiership) • Join lists together Print [1,2,3]+[4,5,6] • Sort lists league.sort()
List Cheat Sheet • list1 + list2 : concatenates list1 and list2 • list[ i ] : access element number i in list. • len( list ) : returns the number of elements in list • del list[ i ] : deletes element number i from list • list.append( value ) : appends value to list • list.sort() : sorts the elements in list • list.reverse() : reverses the order of the elements in list • list.index( value ) : returns the position of the first occurrence of value in list • list.insert( i, value ) : inserts value into list at position i • list.count( value ) : returns a count of the number of times value occurs in list • list.remove( value ) : deletes the first occurrence of value in list • list.pop() : deletes and returns the last value in list • value in list : is True if value occurs in list and False otherwise
Red numbers are:1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36