Lists Methods

Jed Rembold & Fred Agbo

March 6, 2025

Announcements

  • Hopefully, Project 2 - Breakout - is going well
    • Remember, it is due next week Monday at 10pm!
  • Section Leaders will be grading Project 1 by the weekend, I expect their feedback by next week
  • Polling continues here

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)

Mutants

  • The most important difference between strings and lists is one of mutability
    • Strings we have already identified as being immutable: you can not change the individual elements
    • Lists, in contrast, are mutable, which means that we can change or assign new values to the elements of a list
  • Immutable objects have many advantages in programming:
    • You don’t have to worry about if the values will change
    • Immutable values can be more easily shared
    • Immutable objects are easier to use with concurrent programs
  • In some situations though, mutable objects are the perfect tool for the job

A Tutorial on Lists

  • Thinking about mutable objects requires a shift in how we visualize our code interacting with the objects in memory
  • Link here
cool = ['blue', 'violet']
warm = ['red', 'orange']

colors = [cool, warm]
other_colors = [['blue', 'violet'],
                ['red', 'orange']]

print(colors == other_colors)
print(colors is other_colors)

cool[0] = 'indigo'
warm = ['orange', 'yellow']

print(colors)
print(other_colors)

For Reference

  • When working with mutable objects, it is better to think of the variable as holding a reference to the object, rather than the actual contents of the object
  • I find it useful to think of a reference as the “address” in memory where that object’s contents can be found
  • This undeniably complicates things, as referencing a mutable object lets you change it, which will immediately be reflected in anything else that referenced that object
  • Mutable objects can be terrific to work with, as their mutability makes them very flexible, but be wary of unexpected behavior

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