Lists Methods

Jed Rembold & Fred Agbo

March 4, 2024

Announcements

  • Problem Set 4 is due tomorrow Tuesday at 10pm
  • Project 2: Breakout is posted and due next week Tuesday at 10pm!
  • Midterm-1 Exam is being graded.
  • Section Leaders are working on Project 1 feedback
  • Polling continues https://www.polleverywhere.com/agbofred203
    • General poll today! Thus, no need for your names. Just use pseudo-name, nicke-name or initials

Project 2: Breakout!

  • Project 2 is recreating the classic arcade game Breakout!
  • Guide will be posted tomorrow, not due until March 10
  • Focus on the midterm initially, but then consider getting a start this weekend

Breakout History

  • The popular Breakout arcade game was released by Atari in 1976
  • Atari founder Nolan Bushnell wanted a new game that would build on the success of the earlier game Pong. He assigned Steve Jobs to develop the game, promising a bonus if the game required a small number of chips.
  • As Wikipedia tells the story, “Jobs had little specialized knowledge of circuit board design but knew [his friend Steve] Wozniak was capable of producing designs with a small number of chips. He convinced Wozniak to work with him, promising to split the fee evenly between them.”
  • Wozniak completed the game design in four days, but Jobs never told him about the bonus offer. Jobs was paid \(\$5,000\), but Wozniak received only \(\$350\).
  • Jobs and Wozniak co-founded Apple Computer the following year, which has grown to be the largest corporation in the world by market capitalization.

Breakout Basics

  • Breakout is a game in which the player attempts to break all the colored bricks by causing a bouncing ball to collide with them
  • The player controls a paddle at the bottom of the screen which the ball will bounce off
    • The paddle can only move left and right
  • If the ball makes it past the paddle to the bottom of the screen, the player loses a life
    • Lose 3 lives and it is game over!

Breakout Milestones

  • Breakout is broken up over 5 milestones
  • You have already seen or written pieces of similar code to many of the milestones!
    • Milestone 1: PS4 brick pyramid
    • Milestone 3: Section bouncy ball problem (this week)

Milestone 1

Milestone 2

Milestone 3

Milestone 4

Milestone 5

Review Question

Which of the below blocks of code will create the image to the right? The window measures 500 x 200 pixels and the value of d is 150.

 
x, y = 250 - d / 2, 100 - d / 2
a1 = GArc(x, y, d, d, 90, -180)
gw.add(a1)
x, y = 250 - d, 100 - d
a1 = GArc(x, y, d, d, -180, 90)
gw.add(a1)
x, y = 250 - d / 2, 100 - d / 2
a1 = GArc(x, y, d, d, 90, 180)
gw.add(a1)
x, y = 250 - d / 2, 100 - d / 2
a1 = GArc(x, y, d, 180, -90)
gw.add(a1)

Lists as Arguments

  • When you pass a list as an argument to a function or return a list as a result, only the reference to the list is actually passed back and forth
  • This means that the elements of the list are effectively shared between the function and the caller
    • Changes that the function makes to the elements will persist after the function returns
  • Example of reversing a list in PythonTutor: here

Sneaky Mutability

  • List’s mutability can frequently be very nice to work with, but as with lists as arguments to functions, you need to be careful in some instances to ensure you understand how Python is treating the list
  • One could encountered a few other problems where it can be easy to mess up:
    • Initializing a list to look like another list, wanting to make changes and then compare it to the original
    • Looping over a mutating list

Cloning

  • What can we do in these sorts of instances to not let mutability trip us up?
  • Clone the list instead of just assigning a reference
    • Creates a new object in memory
  • Several ways you can make a shallow clone (in code)
    • Using the .copy() list method
    • Any slice always returns a new object
    • Using the list() function will return a new object

Common Useful List Methods

Method Description
list.copy() Returns a new list whose elements are the same as the original
list.append(value) Adds value to the end of the list
list.insert(idx, val) Inserts val before the specified idx
list.remove(value) Removes the first instance of value from the list, or errors
list.reverse() Reverses the order of the elements in the list
list.sort() Sorts the elements of the list. Can take an optional argument key to specify how to sort

List functions on Iterators

  • The .sort and .reverse methods reorder the list in place and do not return anything
  • Commonly, you might want to loop through a list in a particular order, but not change the original list
  • Python gives you two matching functions to do this, which return a new ordered version of the list, without changing the original
    • The reversed() function creates a new iterable object that returns its elements in the opposite order
    • The sorted() function creates a new iterable object that returns its elements in ascending order

List building with loops

  • Commonly will make lists with a simple:

    even_digits = [ 2, 4, 6, 8 ]
  • But in many cases, it is easier to specify the elements of a list using a sequence of values generated by a for loop. For instance

    even_digits = [ ]
    for i in range(0, 10, 2):
        even_digits.append(i)
  • Python gives us a shorthand notation to achieve this:

    even_digits = [ i for i in range(0, 10, 2) ]
    • Called list comprehension

Deleting elements from list

  • Deleting an element from a list is possible with del statement
  • However, in looping through the list:
    • attempt to delete an element while looping will result to IndexError
  • One technique is to create a new list to store all desired element when looping
  • The code below will delete the 4th element in the list
list1 =[2,4,6,5,3]
del list1[3]
print(list1)
  • Code below create a new list of even num
list1 = [2,4,6,5,3]
list2 =[] #to store ele
for i in range(len(list1)):
      if list1[i]%2==0: #remove odd
            list2.append(list1[i])
            
print(list1)
print(list2)
// reveal.js plugins