# list.py # Simple experiment with a list. # We need to be able to: declare, initialize, use. # For more info, see section 5.1 of the Python Tutorial # in the ActivePython 2.6 Documentation. list = [] for i in range(15, 25): list.append(i % 17) print "Here is the list initially" print list # At this point, note the list has 10 elements. # [15, 16, 0, 1, 2, 3, 4, 5, 6, 7] # ------------------------------------------------------- # Let's find the sum of the numbers in the list. # Note the slick way we can iterate thru the list # using the word "in" sum = 0 for value in list: sum += value print "The sum is " + str(sum) # Just to illustrate, you can go thru the list the # old-fashioned way using indices. sum = 0 for i in range(0, 10): sum += list[i] print "The sum is " + str(sum) # Let's find the max and min. max = list[0] min = list[0] for value in list: if value > max: max = value if value < min: min = value print "The max is " + str(max) print "The min is " + str(min) # --------------------------------------------------------------------- # Lists have a built-in sort() function, which doesn't return anything. # Note that if you want to print the list concatenated onto a string, # you need to use str() just like we did with numbers. list.sort() print "Here is the new list: " + str(list) # --------------------------------------------------------------------- # We can search using count() and index(). target = input("Which value would you like to search for?") instances = list.count(target) print str(target) + " appears " + str(instances) + " times in the list." # Note that if the number is not in the list, count will return zero, # but index() will bomb. So, let's protect ourselves. if instances > 0: firstLocation = list.index(target) print "The first instance is at position " + str(firstLocation) # --------------------------------------------------------------------- # Beware of this list pitfall (aliasing error): list2 = list list2[0] = 99 print list print list2 # In both lists, the first element is 99. # What we probably intended was the following: list[0] = 0 # Restore original list[0] value :) list2 = [] for value in list: list2.append(value) list2[0] = 99 print list print list2 # Note that this aliasing error does not happen for simple variable: x = 4 y = x x = 7 print x, y # We see that by changing x, y is not affected.