Comp 112

Lecture 5

Lists and References

2018.02.27

Lists

Lists vs Strings

Lists are similar to strings, but more flexible in two ways:

  1. The elements of a list can be of any type, not just characters.

  2. Lists are mutable: they can be changed after being created.

To write a list, use brackets and commas:

Working with Lists

Homogeneous Lists

List Mutability

Index Assignment

Unlike any type we’ve seen so far, the elements of list type can be changed after being created.

The element located at a list index can be changed using index assignment:

Slice Assignment

A slice can be cut out of a list and a new list spliced into its place using slice assignment:

<list> [<start_index> : <stop_index>]  =  <splice_list>

The list spliced in need not be the same length as the slice cut out.

Aliasing

Aliasing and Mutability

x  =  [1 , 2 , 3]
y  =  x
z  =  [1 , 2 , 3]

If we make changes to a list using one of its aliases then those changes are visible from any other alias too.

Detecting Aliasing

Mutator Functions

List Methods

The list namespace contains functions/methods that act on lists, often by mutation. For example:

All of these can be easily written in just a few lines using slice assignment.

Generic and Higher-Order Functions

Generic List Operations

Python has a built-in function called “reversed” that does the same thing, except that it returns an iterator.

Digression: Iterators

An iterator is any type that can be iterated over with a for loop. lists are examples of iterators.

It is a quirk of Python that many built-in functions that we would expect to return lists actually return other iterators instead.

For example, the range function has signature: int , int -> iterator (int)

All we will care about iterators in this course is that they can be converted to lists.

If indexing into an object that you think is a list causes an error, it may actually be a different iterator instead. Try converting it to a list with the list coercion function.

Mapping over a List

Higher-Order Mapping

Filtering a List

To Do This Week: