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