#---------------------------------------------------------------------- # Building and stepping through lists # # Copyright (C) September 20, 2017 -- Dr. William T. Verts #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Step through a list, printing each element one per line #---------------------------------------------------------------------- def Lister(): L = [4, 5.6, "frog", -3, "toad"] I = 0 while (I < len(L)): print L[I] I = I + 1 return #---------------------------------------------------------------------- # Three forms of the range function: # # range(N) generates list [0,1,2,3, ..., N-1] # range(10) gives [0,1,2,3,4,5,6,7,8,9] # # range(M,N) generates list [M,M+1,M+2,M+3, ..., N-1] # range(10,20) gives [10,11,12,13,14,15,16,17,18,19] # # range(M,N,P) generates list [M,M+P,M+2P,M+3P, ..., N-1] # range(10,20,3) gives [10,13,16,19] #---------------------------------------------------------------------- #---------------------------------------------------------------------- # Build a list of squares of numbers from 0 to 10. # # Method #1: Build a list containing [0,1,2,3,...,10], step through # that list squaring each entry. Does NOT work with tuples! #---------------------------------------------------------------------- def BuildSquares(): L = range(11) # L = [0,1,2,3,4,5,6,7,8,9,10] I = 0 while (I < len(L)): L[I] = L[I] * L[I] I = I + 1 return L #---------------------------------------------------------------------- # Build a list of squares of numbers from 0 to 10. # # Method #2: Start with an empty list L, step through the integers # from 0 through 10, and add a list with the square of each integer # to the end of L. #---------------------------------------------------------------------- def BuildSquares2(): L = [] I = 0 while (I < 11): L = L + [I*I] # L is a list, so I*I has to be in a list I = I + 1 return L #---------------------------------------------------------------------- # Build a list of squares of numbers from 0 to 10. # # Method #3: Start with an empty list L, step through a range of # numbers from 0 through 10, and add a list with the square of each # integer to the end of L. # The for-loop steps the control variable (I in this case) through # the elements of a list, one value for each pass through the loop. # The list to step through can be an explicit list (3a) or the # result of a range (3b, more common). #---------------------------------------------------------------------- def BuildSquares3a(): L = [] for I in [0,1,2,3,4,5,6,7,8,9,10]: L = L + [I*I] return L def BuildSquares3b(): L = [] for I in range(11): L = L + [I*I] return L #---------------------------------------------------------------------- # On Friday we will expand on 3b to do the whole task in a single # Python statement, called a list comprehension. #----------------------------------------------------------------------