"""Lists http://openbookproject.net/thinkcs/python/english2e/ch09.html """ # A list is an ordered set of values, where each value is identified by an index. # The values that make up a list are called its elements. # Lists are similar to strings, which are ordered sets of characters, except that # the elements of a list can have any type. # use the bracket notation to create a list: vocabulary = ["ameliorate", "castigate", "defenestrate"] numbers = [17, 123] empty = [] # The elements of a list don't have to be the same type: mixed_list = ["hello", 2.0, 5, [10, 20]] # Elements of a list are accessed using the bracket operator, the same way the characters # of a string. # Remember that the indices start at 0: print numbers[0] # the index can't be larger than the length of the list - 1: print numbers[2] # Any integer expression can be used as an index: print numbers[9-8] # but the expression needs to be an integer value: print numbers[1.0] # If an index has a negative value, it counts backward from the end of the list: print numbers[-1] print numbers[-2] print numbers[-3] # it is common to iterate through the elements of a list using a for loop: # (note the useage of len() to obtain the length of a list) vocabulary = ["ameliorate", "castigate", "defenestrate"] for i in range(len(vocabulary)) : print vocabulary[i] # or: for word in vocabulary : print word # list membership is determined using the in operator: 'castigate' in vocabulary 'word' in vocabulary # list operations # the + operator concatenates lists: a = [1, 2, 3] b = [4, 5, 6] c = a + b print c [0] * 4 # Slices # The slice operations we saw with strings also work on lists: a_list = ['a', 'b', 'c', 'd', 'e', 'f'] a_list[1:3] a_list[:4] a_list[3:] a_list[:] # Unlike strings, lists are mutable, which means we can change their elements # using the bracket operator: fruit = ["banana", "apple", "quince"] fruit[0] = "pear" fruit[-1] = "orange" # del removes an element from a list: a = ['one', 'two', 'three'] del a[1] print a #You can use a slice as an index for del: a_list = ['a', 'b', 'c', 'd', 'e', 'f'] del a_list[1:5] print a_list