#!/usr/bin/python3 # Accessing List elements. dogNames = [ "harry", "Shenanigans","katrina","Tanner","Yukon Jack", "Colorado","Mandy"] firstNames = ["edward","david", "Bob","mary","alice"] txtList = ["7", "2", "12", "18", "16", "21"] intList = [7, 2, 12, 18, 16, 21] primeList = [1, 2, 3, 7, 11, 13, 17, 19] # Same list print as in the first program. print (dogNames," length = ",len(dogNames)) print(firstNames," length = ",len(firstNames)) print(intList," length = ",len(intList)) print(primeList," length = ",len(primeList)) print(txtList," length = ",len(txtList)) # Access each element in a list. # The index starts at 0 # If you uncomment '#print(dogNames[7])' the program will # generate an error. There is no element #7 print (dogNames," length = ",len(dogNames)) print("\nOutput for each element index.") print(dogNames[0]) print(dogNames[1]) print(dogNames[2]) print(dogNames[3]) print(dogNames[4]) print(dogNames[5]) print(dogNames[6]) #print(dogNames[7]) # Access elements from the end of the list. Use # negative numbers to access the values starting at the end of the list. print (dogNames," length = ",len(dogNames)) print("\nOutput for each negative element index.") print(dogNames[-1]) print(dogNames[-2]) print(dogNames[-3]) print(dogNames[-4]) print(dogNames[-5]) print(dogNames[-6]) print(dogNames[-7]) #print(dogNames[-8]) # We are getting ahead of ourselves, but we can examine the for loop # to print the elements of the list. This loop determines the length # of the list and processes every element. # Starting with the first element in the list each element in the list will # be assigned to aDogName. You ca do anything you like with this one element. print("\n") print (dogNames," length = ",len(dogNames)) print("\nOutput from the for loop") for aDogName in dogNames: print(aDogName) print("\n") # Slices aloow one to access a group of elements from the list. print (dogNames," length = ",len(dogNames)) print("\nPrint list slices. Notice the slice is a new list.") # Print elements 1 through element 4 print(dogNames[1:4]) # Print elements 4 through the end of the list print(dogNames[4:]) # Print elements from the start of the list through element 4 print(dogNames[:4])