def traverseList(): for element in ['a', 2, 'word', ['1,2', 3]]: if type(element) == list: print('list of length:', len(element)) else: print(element) def traverseList2(l): for number in l: if number < 0: print("negative") else: print("not negative") # Example of building and returning a new list # # Returns a new list containing the negative numbers that appear in the # input list # def negativeListFrom(l): result = [] for number in l: if number < 0: print("before", result) result = result + [number] #result.append(number) print("after", result) return result # assume list1 and list2 are equal length lists of numbers # return a list where the ith item is the larger of the ith items # of list1 and list2 # def listOfBiggests(list1, list2): newList = [] index = 0 while index < len(list1): if list1[index] > list2[index]: newList = newList + [list1[index]] else: newList = newList + [list2[index]] index = index + 1 return newList def listOfBiggests2(list1, list2): newList = [] index = 0 for index in range(len(list1)): item1 = list1[index] item2 = list2[index] if item1 > item2: newList.append(item1) else: newList.append(item2) return newList # listOfLists is a list containing 0 or more lists of numbers # Return a new list that is the same length as listOfLists but where # the ith element of the result is the average of all the numbers # in the ith element of listOfLists # # When does this work/not work? Is the specification clear enough to know? # def getAverages(listOfLists): averages = [] for sublist in listOfLists: # compute average for sublist sublistSum = 0 for item in sublist: sublistSum = sublistSum + item # append sublist average to result averages.append(sublistSum/len(sublist)) return averages