Week 8: Lists

Reading: Think Python Chapter 10

Notes

Sequences

  • Lists are sequences.
  • Lists can contain a mix of different types
  • Much of what you learned about strings as sequences is also true of lists.
  • Lists are delimited with square brackets:
L = [2, 4, 'resonant', -1.2]
  • Lists are indexed with square brackets, identical to string indexing:
L[2]
'resonant'
L[1:3]
[4, 'resonant']
  • Unlike strings, lists are mutable. Values can be assigned in to lists:
L[1] = 'dampened'
L
[2, 'dampened', 'resonant', -1.2]

The len function also works for lists:

len(L)
4

Operators, Functions, Methods

Operators work with lists somewhat similarly to how they work with strings:

  • + between two lists concatenates the lists and returns a new list
[4, "3"] + [2, 1]
[4, '3', 2, 1]
  • A list can be “multiplied” with an integer using *
[0] * 6
[0, 0, 0, 0, 0, 0]

Lists have built-in methods, similar to strings. One of the most useful of these is <list>.append()

fruit = ['apple', 'pear', 'mango']
fruit.append('tomato')
fruit
['apple', 'pear', 'mango', 'tomato']

<list>.sort() will sort numeric values as you would expect:

numerical_sort,py
number_list = [1, 5, 6, 10, 2]
number_list.sort()
print(number_list)
[1, 2, 5, 6, 10]

It sorts strings and characters a bit differently:

alpha_sort,py
alpha_list = ['apple','Banana', 'Pear', 'mango', ' CHICKEN']
alpha_list.sort()
print(alpha_list)
[' CHICKEN', 'Banana', 'Pear', 'apple', 'mango']

What happened? In Python, every character is associated with an integer. This mapping is known as ASCII. Functions ord() and chr() convert between characters and numbers.

ord('A')
65
ord('b')
98
ord('@')
64
chr(99)
'c'

Comparing and sorting strings/characters uses these values. You will never need to memorize them.

Iterating

Iterating through lists is very similar to iterating through strings:


There are some differences, largely because lists are mutable:

Why was no 8 printed?


Very importantly when you iterate directly through the elements of a list with content iteration, the looping variable is a temporary copy of the list element. Changing that temporary variable does not change the list!

On the other hand, using value iteration, you can directly access and change list elements.

References

When a ‘primitive’ type is assigned to a variable, the value is assigned directly to the variable. When a list is assigned to a variable, the variable becomes a reference to the list. If two variables are assigned to the same list, changing one variable effectively changes the other- since you are changing the list that both variables reference.

Here’s an example:

You can check if two variables reference the same list with the is keyword:

a = [1, 2]
b = [1, 2]
c = a
a == b
True
a is b
False
a is c
True

The == operator between lists checks if the contents of two lists are the same, the is keyword checks if two variables reference the same list. This a subtle, but important difference.

Lists and Functions

Similarly, passing a list as an argument to a function passes a reference to this list. If your function modifies the referenced list inside the function, the list is modified outside the function as well.

Note how the add_to_list function modified the list without returning anything.

Practice

Practice Problem 8.1

Practice Problem 8.1

Write a function appendix that takes as argument a list, appends integer 9 to the list, and returns the list.

  • appendix(['cat', 'dog']) should return ['cat', 'dog', 9]

Practice Problem 8.2

Practice Problem 8.2

Write a function round_floats that takes as argument a list of floats. The function should create a new list, consisting of the elements of the argument list, rounded to the nearest integer. Return the new list.

  • round_floats([1.2, 1.7, 3.1]) should return [1, 2, 3]
  • round_floats([-1.2, 2.4, 2.5]) should return [-1, 2, 3]

Practice Problem 8.3

Practice Problem 8.3

Write a function round_only_floats that takes as argument a list. The function should create a new list, consisting of the elements of the argument list, with any floats rounded to the nearest integer, and other elements (which are not floats) unchanged. Return the new list.

  • round_only_floats([1.2, 1.7, 3.1]) should return [1, 2, 3]
  • round_only_floats([-1.2, 'clouds', 2.5]) should return [-1, 'clouds', 3]
  • round_only_floats(['mice', 'rats']) should return ['mice', 'rats']

Practice Problem 8.4

Practice Problem 8.4

Write a function positives that takes as argument a list of ints. The function should create a new list, consisting of the positive elements of the argument list, in the same order. Return the list.

  • positives([3, -1, 2]) should return [3, 2]
  • positives([-4, 5, -2, 5]) should return [5, 5]
  • positives([-1, -8]) should return [] (an empty list)

Practice Problem 8.5

Practice Problem 8.5

Write a function total_length that takes as argument a list of strings, and returns the total length of all the strings combined.

  • total_length(['cat', 'dog']) should return 6
  • total_length(['house', 'shed']) should return 9
  • total_length(['3', '2']) should return 2

Homework

  • Homework problems should always be your individual work. Please review the collaboration policy and ask the course staff if you have questions.

  • Double check your file names and return values. These need to be exact matches for you to get credit.

Homework Problem 8.1

Homework Problem 8.1 (20 pts)

Write a function list_reverse that takes as argument a list, and returns a list with the same elements, in reversed order.

  • list_reverse([2, 3, 5]) returns [5, 3, 2]
  • list_reverse(["maple", "cherry", "ash", "oak"]) returns ["oak", "ash", "cherry", "maple"]
  • list_reverse([]) returns [] (an empty list)

Submit as list_reverse.py.

Homework Problem 8.2

Homework Problem 8.2 (20 pts)

Write a function even_less that takes as argument an integer and returns a sequentially-increasing list of even integers starting at 0, ending with the argument (if the argument is even) or with one less than the argument (if the argument is odd). The argument will always be a positive integer.

  • even_less(6) returns [0, 2, 4, 6]
  • even_less(9) returns [0, 2, 4, 6, 8]
  • even_less(1) returns [0]

Submit as even_less.py.

Homework Problem 8.3

Homework Problem 8.3 (20 pts)

Write a function numbers_first that takes as argument a list of numbers and/or strings, and returns a list with the same contents, but all numbers come before all strings. Original order should otherwise be preserved.

(“Numbers” here are either ints or floats.)

  • numbers_first([1, 3.0, 'soap', 0]) returns [1, 3.0, 0, 'soap']
  • numbers_first(['brooms', 4, 'towels']) returns [4, 'brooms', 'towels']
  • numbers_first([15, 2, 'sponge']) returns [15, 2, 'sponge']
  • numbers_first([1, 2, 0]) returns [1, 2, 0]
  • numbers_first(['three', 'two']) returns ['three', 'two']

Submit as numbers_first.py.

Homework Problem 8.4

Homework Problem 8.4 (20 pts)

Write a function zip_finder that takes as argument a list. Exactly one element of the list will be a zip code: a positive five-digit integer. Return that integer.

Type hint: the return value should be an integer

  • zip_finder([1, 4, 'Alan', 20052]) returns 20052
  • zip_finder([False, 20003, -5, "DC"]) returns 20003
  • zip_finder(["Carl", 854.22, 10001.2, -2000, 86004]) returns 86004

Submit as zip_finder.py.

Homework Problem 8.5

Homework Problem 8.5 (20 pts)

Write a function flip_smallest that takes as argument a list of strings. Find the shortest of these strings and reverse it.

Your function should modify the argument list in place and does not need to return anything. You can assume there will only be one “shortest” string in each list, and that the shortest string will be at least two characters in length.

Examples:

a = ['easy', 'to', 'say']
flip_smallest(a)
print(a)
['easy', 'ot', 'say']
b = ['contains', 'plastic', 'parts']
flip_smallest(b)
print(b)
['contains', 'plastic', 'strap']
c = ['some', 'kinds', 'are', 'easier', 'than', 'others']
flip_smallest(c)
print(c)
['some', 'kinds', 'era', 'easier', 'than', 'others']

Submit as flip_smallest.py.

  • Find the shortest string:
    • Visit each element in the list
    • Use the len() function to check lengths
    • Use a variable to remember the shortest length you have found
    • Use a second variable to remember the index associated with that length
    • Update both variables if you find a new shorter length
  • Now that you know where the string is (the index you found):
    • Create a new string, the reverse of the original
    • Assign it into the list in the correct position