'''lecture_13_lists.py Shows how to use lists. Make sure that you understand what everything here does. Oliver W. Layton CS 151: Computational Thinking: Visual Media Spring 2021 ''' import turtle import random '''Creating lists''' # Items in list enclosed by square brackets [] and each item separated by a comma # aList = [1, 2, 99, -500] # print(aList) # A list can hold items with a mix of any data types, including objects # myScreen = turtle.Screen() # turt = turtle.Turtle() # myList = [10, -2.0, False, 'hi CS151!', myScreen, turt] # Use print to see what's in a list # print('Here is my list', myList) '''Accessing items''' # You also use square brackets to access items in the list # Place them to the right of the list variable name and use an int to get the i-th item # NOTE: Counting starts with 0, not 1. 1st item at position 0, 2nd item at position 1, ... # Get the 1st, 2nd, and 4th items # print(myList[0]) # print(myList[1]) # print(myList[3]) # NOTE: These ints that tell us the position in the list we want to access an item # is called an INDEX # You can assign an item (after accessing it) to a new variable # myInt = myList[0] # print('myInt is:', myInt) # Need to access items near the end of the list? Use negative indices # Print out the last and 2nd to last items # print(myList[-1]) # access last item # print(myList[-2]) # 2nd to last item '''How many items do I have in a list?''' # Use the `len` function to get the length of the list (how many items it has) # NOTE: `len` is a FUNCTION, not a METHOD # print('The length of my list is: ', len(myList)) # function: function(parameter1, parameter2) #len(myList) # method: called on object. Doesn't actually work, but showing that methods are functions # called ON objects. object.method() #myList.len() '''Slicing''' # You can access multiple items in a list and get a smaller list back using slicing # Slicing uses 1 or 2 colons inside the square brackets # Use slicing to access and print 1st 3 items in a list # NOTE: Position of int BEFORE : is INCLUDED. Position of int AFTER : EXCLUDED # Print out the 1st 3 things in numList # print(numList[0:2]) # Take items at index 0 to 2 # print(numList[0:3]) # Right endpoint index NOT INCLUDED numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # Assign items 3 thru 5 to another variable, print it # Print 1st and last three items threeItems = numList[2:5] # item 3 is at index 2 # Remember: right index is not included. # print(threeItems) # Print out the 1st 3 things in numList # print(numList[-3:-1]) # would EXCLUDE the last item bc right endpoints are not included # print(numList[-3:]) # print(numList[:3]) # same as numList[0:3] # print(numList[0:3]) # print(numList[:]) # access items in the list begining to end # Shorthand: Can omit index before or after colon if position of beginning or end of list included # Print 1st and last three items # Print out the 1st 3 things in numList # print(numList[:3]) # same as writing print(numList[0:3]) # print(numList[4:]) # Takes out items at index 4 to the end of the list # Print every other item in a list (e.g. all items including omitting last one, also ALL items) # print(numList) # print(numList[0:10:2]) # print(numList[0:11:2]) # including the last number # print(numList[0:11:3]) # print(numList[::3]) # same as last line, going beginning to end, so can leave out left/right indices around : # Reverse a list (make back front, make front back) using negative "step" value # print(numList[::-1]) '''Looping through a list''' # Until now, we've been using range to write a for loop # for i in range(10): # print(i) # What is range? Range actually acts like a list. # Let's force range to reveal itself as a list: # print(list(range(10))) # So when we write a loop with range, it's essentially using a list like this: # for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: # print(i) # We can loop thru any list by replacing range with the list. # NOTE: The loop variable (e.g. i) BECOMES EACH ITEM, not the iteration number! # abcs = ['a', 'b', 'c'] # for letter in abcs: # print(letter) # Let's make a screen and 4 turtles # add them to a list, then move them to a random location with a loop # myScreen = turtle.Screen() # turt1 = turtle.Turtle() # turt2 = turtle.Turtle() # turt3 = turtle.Turtle() # turt4 = turtle.Turtle() # myPets = [turt1, turt2, turt3, turt4] # for turt in myPets: # turt.goto(400*random.random() - 200, 400*random.random() - 200) # myScreen.exitonclick() # An option: (not required) # myScreen = turtle.Screen() # myPets = [turtle.Turtle(), turtle.Turtle(), turtle.Turtle(), turtle.Turtle()] # for turt in myPets: # turt.goto(400*random.random() - 200, 400*random.random() - 200) # turt1 = myPets[0] # turt1.color('blue')s # myPets[0].color('blue') # myScreen.exitonclick() # When we want to loop thru multiple lists at once, it is easiest to use range (with an index) # Let's move back the turtles back to the origin then move them to the following coordinates x = [-200, -100, 100, 200] y = [200, 100, -100, -200] # myScreen = turtle.Screen() # turt1 = turtle.Turtle() # turt2 = turtle.Turtle() # turt3 = turtle.Turtle() # turt4 = turtle.Turtle() # myPets = [turt1, turt2, turt3, turt4] # # print(list(range(3))) # for i in range(len(myPets)): # # turt = myPets[i] # # turt.goto(x[i], y[i]) # myPets[i].goto(x[i], y[i]) # myScreen.exitonclick() '''Adding/updating/removing items from an existing list''' # You can use assignment to update one item of a list at a time myNumlist = list(range(5)) # print(myNumlist) # Let's use this to update a list with 2 added to every item in the list for i in range(len(myNumlist)): myNumlist[i] = myNumlist[i] + 2 # print(myNumlist) # Two VERY IMPORTANT methods for lists, and two less common ones, but still good to know # 1) append: Useful to building a list. Add item to the END of a list # 1st: Build list with loop index # 2nd: Efficiently make a number of turtles and add them to a list myints = [] myPets = [] # print('myints empty:', myints) # print('myints lengh:', len(myints)) for i in range(6): myints.append(i) # print('In loop. adding', i, 'to myints:', myints) # print('After appending i values to myints:', myints) # want to make/add 10 turtles for i in range(10): turt = turtle.Turtle() myPets.append(turt) # print(myPets) # print(len(myPets)) # 2) pop: Remove items from the END of the list. "Undo" what append does # Pop off a few items from int and turtle lists # print(myints) myints.pop() myints.pop() # print(myints) myPets.pop() # print(len(myPets)) # pop returns the item that is removed, in case we want to assign it to a variable removed = myints.pop() # print('This is what was removed:', removed) # print(myints) # 3) insert: Lets you add an item at a position in the list # There are two parameters: .insert(, ) # NOTE: The insert method doesn't return anything, it modifies the list that you put before the . # Add add a string to the 2nd position (index 1) of the list myints.insert(0, -99) myints.insert(2, -98) # print(myints) # 4) extend: let's you merge a second list into an existing one # NOTE: The extend method doesn't return anything, it modifies the list that you put before the . # print(myints) letters = ['a', 'b', 'c'] myints.extend(letters) # print(myints) '''Containment''' # In a conditional statement, you can use the 'in' keyword to check whether a thing is an item in # a list nums = list(range(10)) # print(nums) valueTheCheck = 8 # if valueTheCheck in nums: # print('8 is in the list!') # else: # print('8 is not in the list!') # You can use 'not' keyword to check is something is NOT in the list # if 99 not in nums: # print('99 is not in the list!') # else: # print('99 is in the list!') # if 5 not in nums: # print('5 is not in the list!') # else: # print('5 is in the list!') '''Using operators on lists''' # You can use some math operators on lists, but they don't do math operations # Plus concatenates (glues together) two lists — e.g. nums and letters letters = ['a', 'b', 'c'] # letters = letters + letters letters = letters + [1, 2, 3, 4, 5] # print(letters) # Times replicates a list simple = [1, 2, 3] simple = simple*3 # print(simple) # Make a list of 10 0s zeros = 10*[0] # print(zeros) # print(len(zeros)) # NOTE: Be careful, many math operators not defined / don't work # print(zeros/3) '''Lists passed in and returned from functions''' # Lists act like object when passed into functions as parameters and returned from them # Example: function that doubles all values of list def double(theList): for i in range(len(theList)): theList[i] = 2*theList[i] return theList aList = [1, 2, 3] #['a', 'b', 'c'] aList = double(aList) print(aList)