#list_ints.py #demo list of ints scores = [] #is empty, i.e. no elements, length is 0 n = eval(input("Enter the number of scores you have: ")) for i in range(n): num = eval(input("Enter a score: ")) scores.append(num) #display as a list [v1,v2,...,vn] print(scores) print(type(scores)) print("Length of scores list:", len(scores)) #access each element using in operator. "traverse" the list for scor in scores: print(scor, end=" ") print() #use index to access each element for i in range(len(scores)): print(i, ":", scores[i]) # scores[i] # i must be between 0 and len(scores)-1, inclusive, else IndexError crash. #scores[4] = "asdf" print("Sum=",sum(scores)) #all elements must be numbers print("Count=",len(scores)) print("Max=",max(scores)) #all elements must be same type print("Min=",min(scores)) # " print("Average=",sum(scores)/len(scores)) print("Range=",max(scores)-min(scores)) #(repeatedly) search a list. There is no .find() method! item = eval(input("Enter number to search for in the array: (-999 to quit) ")) while item != -999: if item in scores: print("Found it (first) at index:", scores.index(item)) #index: must exist! print("#times in the list:", scores.count(item)) #count: 0 OK else: print("not found") print("#times in the list:", scores.count(item)) #count: 0 OK item = eval(input("Enter number to search for in the array: (-999 to quit) ")) #reverse the list (does not sort) scores.reverse() print(scores) #sort the list. Type of elements must be same. scores.sort() print(scores) #inserting scores.insert(index,value) #Deleting elements: # pop() deletes and returns the last element lastone = scores.pop() print(lastone) #list is one shorter print(scores, " Length:", len(scores)) # pop(index) deletes and returns the index_th element. Any element. del_i = int(input("Enter the index of the element to remove from the list: ")) removed = scores.pop(del_i) print(removed) print(scores, " Length:", len(scores)) # delete an element with the del keyword #del scores[i] # delete a known existing value. Error if doesn't exist in the list #scores.remove(92) # copy. 3 ways new_list = scores.copy() new_list = list(scores) new_list = scores[:] #do something to each element, e.g. divide each score by 2 for i in range(len(scores)): scores[i] = scores[i] // 2 print(i, ":", scores[i]) print(scores)