Day 5: Advanced Lists and Loops

back · home · slides · CMSC 201 (Fall 2024) @ UMBC · for _ in range(10): print('pyyyythonn')

CMSC 201: Lists and Loops P2

Agenda:

  • Any more HW2 questions?
  • "Fun": code golfing
  • Who cares? (AKA: what will we make)
  • Advanced lists/loops
  • While loops
  • Goal: Understand lists and loops VERY well; be able to write a loop or use lists for anything! Maybe have some fun :)

    My email is: sdonahue@umbc.edu (Shane Donahue), office hours Tu/Th ITE 373 2-3PM

    HW2

    HW2... still here

    Still exists. Still due 2024-09-20 23:59.99999.... Any more questions?

    "Fun": code golfing

    Golfing, fewest hits (strokes) to get the ball in the hole wins...

    ...code golfing, fewest keystrokes wins?

    Code Golf stack exchange Tips for Code Golfing in Python

    Please don't code golf your homework or labs (lol).

    Who cares (about more lists and loops)?

    We have the power of all loops and lists! What shall we make with it... uhhh.... magic 8 ball? Context-specific magic 8ball. Imagining: a list of possible fortunes, only some of them applicable. Filter list and then select random element.

    Advanced lists and loops

    Review: Lists let you store lists of things! Here are some letters :)

    my_favorite_letters = ["a", "b", "c", "p", "y"]

    Review: we can iterate through lists! Here's a for loop:

    for x in my_favorite_letters:
        print(x)
    

    Review: range(start, stop, step)

    You can think about range like a function that returns a list of numbers. Important to be precise about inputs to range. start by default is 0. stop is exclusive, meaning the value itself IS NOT included, and start is inclusive, meaning the value IS included.

    # 0 through 9
    range(10)
    # 0, 2, 4, 6, 8, 10
    range(0, 11, 2)
    

    Append & Friends

    You can add to the end of a list by appending to it.

    my_favorite_numbers = [1, 1, 2, 3, 5, 8, 13]
    # Add a new element!
    my_favorite_numbers.append(21)
    # Print the list
    print(my_favorite_numbers)

    The list operations to know:

    Append: add to end of list (my_favorite_letters.append("x"))

    Insert: add to index (my_favorite_letters.insert(1, "z"))

    Pop: return and remove last element or at given index (also see pop's strange cousin: del) (my_favorite_letters.pop()))

    Remove: delete an element by value (my_favorite_letters.remove("a"))

    Challenge: add every number from 0 to 100 that is divisible by three to a list. Then, remove all the numbers divisible by 5.
    output_nums = []
    # loop of 0 to 100
    for x in range(101):
        # add to list if divisible by 3 and not 5
        if x % 3 == 0:
            output_nums.append(x)
            
    for x in range(101):
        if x % 5 == 0:
            output_nums.remove(x)
        
    print(output_nums)

    Modifying lists: what's wrong with this code?

    # Remove all even values
    my_favorite_numbers = [1, 2, 6, 4, 8, 6, 7, 8]	
    for num in my_favorite_numbers:
        if num % 2 == 0:
            my_favorite_numbers.remove(num)
    

    The list changes as it's iterating through it! 😱

    Pass by reference/pass by value

    Very technically, python does neither pass by value or pass by reference... but we don't need to worry about that! It's helpful to think of it in this way, and it transfers well to other languages...

    Pass by reference: passing a "pointer", or reference to the original object

    Pass by value: passing the "value", or a copy of the original object

    Advanced slicing

    What if we want a sub-list? Slicing can give us a copy of a sub-list. The colon in the middle separates our start and end indicies.

    my_favorite_letters = ["a", "b", "c", "p", "y"]
    # Give me the first three
    print(my_favorite_letters[:3])

    What does this do?

    my_favorite_letters = ["a", "b", "c", "p", "y"]
    new_list = my_favorite_letters[:]

    Taking a slice of the whole list will make a copy.

    Double colon syntax: it's just like the range function! your_list[start:stop:step].

    Challenge: Make a list of every letter. Then, print out every even index letter... backwards.
    letter_list = []
    for x in range(97, 123):
        # ASCII encoding: chr(97) == a
        letter_list.append(chr(x))
    
    print(letter_list[len(letter_list)-2::-2])

    Multi-dimensional lists

    You can nest for loops! This is helpful for instantiating multi-dimensional lists.

    Challenge: Make a 2D (two dimensional) array with 8 rows and 8 columns.
    board = []
    for x in range(8):
        board.append([])
        for y in range(8):
            board[-1].append("")

    What's the difference between these programs?

    for i in board:
        for j in i:
            j = "X"
            print("The board element is", j)
    for i in range(len(board)):
        for j in range(len(board[i])):
            board[i][j] = "X"
            print('The board at', i, j, 'is', board[i][j])

    The top one is a for-each loop, using a copy of the list elements (pass by value), and the bottom one is a for loop, referencing the original lists. To do that, the bottom one needs the list indicies (indexes).

    The "in" operator (membership test)

    You can use this to test if something is in a list.

    my_favorite_numbers = [1, 1, 2, 3, 5, 8, 13]
    3 in my_favorite_numbers # True

    You can also use it to test if something is a "substring".

    "cool" in "cool beans" # True

    While loops

    For loops are cool and all, if you have a list or iterator (like range) to go through. But what if you want to test for a boolean condition?

    While loops are the answer!

    while input() != "y": print("please type y")
    Challenge: Ask the user for an odd number until they give you one. (While the number is odd, ask for input.)

    Magic 8 Ball

    Oh wise magic 8 ball... We want: a list of possible fortunes, only some of which are applicable. Filter list and then select random element to tell fortune.

    # magic8ball
    import random
    
    fortunes = ["weather is good", "weather is bad", "the weather will be a firestorm", "homework will be easy", "homework will be hard"]
    valid_fortunes = []
    
    user_preference = input("What type of fortune do you want: ")
    
    for f in fortunes:
        if user_preference in f:
            valid_fortunes.append(f)
    
    selected_element = int(random.random() * len(valid_fortunes))
    print("Your fortune is:", valid_fortunes[selected_element])