'''lecture_12_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 Fall 2020 ''' import turtle import random '''Creating lists''' # Items in list enclosed by square brackets [] and each item separated by a comma myInts = [9, 99, -500, -1, 0] # A list can hold items with a mix of any data types, including objects # screen = turtle.Screen() # turt = turtle.Turtle() # myList = [99, True, 'hi!', turt, 2.0, -5, screen] # 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[2]) # 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 # myString = myList[2] # print(myString) # 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]) # print(myList[-2]) '''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(len(myList)) '''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 numList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] # first1 = numList[0:1] # print(first1) # first3 = numList[0:3] # print(first3) # NOTE: Position of int BEFORE : is INCLUDED. Position of int AFTER : EXCLUDED # Assign items 3 thru 5 to another variable, print it # [1, 2, *3, 4, 5*, 6, 7, 8, 9, 10, 11] # print(numList[2:5]) # Shorthand: Can omit index before or after colon if position of beginning or end of list included # Print 1st and last three items # print(numList[:3]) # print(numList[-3:]) # Print every other item in a list (e.g. all items including omitting last one, also ALL items) # print(numList[0:-1]) # print(numList[0:-1:2]) # print(numList[::2]) # 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) # i = rangeList[0] # i = rangeList[1] # i = rangeList[2] # 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 # screen = turtle.Screen() # turt1 = turtle.Turtle() # turt2 = turtle.Turtle() # turt3 = turtle.Turtle() # turt4 = turtle.Turtle() # turtles = [turt1, turt2, turt3, turt4] # for turt in turtles: # turt.goto(600*random.random()-300, 600*random.random()-300) # 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] # colors = ['red', 'blue', 'pink', 'orange'] # print(len(turtles)) # for i in range(len(turtles)): # print(i) # turtles[i].goto(0, 0) # same as turt1.goto(0, 0), ... # turtles[i].color(colors[i]) # turtles[i].goto(x[i], y[i]) # screen.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)) # myNumlist[1] = 999 # 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 # myList = ['a', 'b'] # myPets = [] # for i in range(3): # myList.append(i+2) # turt = turtle.Turtle() # myPets.append(turt) # print(myList) # print(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 # myList.pop() # myList.pop() # print(myList) # pop returns the item that is removed, in case we want to assign it to a variable # theOne = myList.pop() # print('This is what was removed:', theOne) # print(myList) # 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 = [99, 100, 101] # myInts.insert(0, 'a') # myInts.insert(0, 'b') # myInts.insert(0, 'c') # myInts.insert(-2, 'the end?') # myInts.append('the end?') # print(myInts) # to replace, use assignment #myInts[0] = -100 #myInts[3] = 99999 # doesnt work, nothing in index 3. WOuld need to use append to add to end # 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 . # myList = [99, 100, 101] # thingsToAdd = [9, 99, 999] # myList = [True, True, False] # thingsToAdd = ['hi', 'there', 'cs151'] # myList.extend(thingsToAdd) # print(myList) '''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)) # fruit = 'apple' # nums.append(fruit) # print(nums) # if 'apple' in nums: # print('apple is in the list!') # else: # print('apple is not in the list!') # You can use 'not' keyword to check is something is NOT in the list # nums.append('pear') # if 'pear' not in nums: # print('pear is not in the list!') # else: # print('pear 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 # nums = [] # for i in range(10): # nums.append(i) # print(nums) # print(list(range(10))) # letters = ['a', 'b', 'c'] # letters.extend([1, 2, 3]) # print('with extend', letters) # letters = ['a', 'b', 'c'] # # letters = letters + [1, 2, 3] # letters + [1, 2, 3] # print('With +', letters) # Times replicates a list # simple = [1, 2, 3] # print(simple*100) # Make a list of 10 0s # ten0s = [0]*10 # print(ten0s) # NOTE: Be careful, many math operators not defined / don't work # print(ten0s/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] print(aList) aList = double(aList) print(aList)