If a refers to an object and you assign b = a, then both variables refer to the same object. To check whether two variables refer to the same object, you can use the is operator:
The association of a variable with an object is called a reference. In this example, there are two references to the same object.
An object with more than one reference has more than one name, so we say that the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:
Although this behavior can be useful, it is error-prone. In general, it is safer to avoid aliasing when you are working with mutable objects.
For immutable objects like strings, aliasing is not as much of a problem. In this example:
It almost never makes a difference whether a and b refer to the same string or not.
When you pass a list to a function, the function gets a reference to
the list. If the function modifies the list, the caller sees
the change. For example, delete_head
removes the first element
from a list:
Here’s how it is used:
The parameter t and the variable letters are aliases for the same object. The stack diagram looks like Figure 21.2.
Since the list is shared by two frames, I drew it between them.
It is important to distinguish between operations that modify lists and operations that create new lists. For example, the append method modifies a list, but the + operator creates a new list.
Here’s an example using append:
The return value from append is None.
Here’s an example using the + operator:
The result of the operator is a new list, and the original list is unchanged.
This difference is important when you write functions that are supposed to modify lists. For example, this function does not delete the head of a list:
The slice operator creates a new list and the assignment makes t refer to it, but that doesn’t affect the caller.
At the beginning of bad_delete_head
, t and t4
refer to the same list. At the end, t refers to a new list,
but t4 still refers to the original, unmodified list.
An alternative is to write a function that creates and returns a new list. For example, tail returns all but the first element of a list:
This function leaves the original list unmodified. Here’s how it is used:
Careless use of lists (and other mutable objects) can lead to long hours of debugging. Here are some common pitfalls and ways to avoid them:
Most list methods modify the argument and return None. This is the opposite of the string methods, which return a new string and leave the original alone.
If you are used to writing string code like this:
It is tempting to write list code like this:
Because sort returns None, the next operation you perform with t is likely to fail.
Before using list methods and operators, you should read the documentation carefully and then test them in interactive mode.
Make copies to avoid aliasing.
If you want to use a method like sort that modifies the argument, but you need to keep the original list as well, you can make a copy.
In this example you could also use the built-in function sorted, which returns a new, sorted list and leaves the original alone.
A sequence of values.
One of the values in a list (or other sequence), also called items.
A list that is an element of another list.
A variable used in a loop to add up or accumulate a result.
A statement that updates the value
of a variable using an operator like +=
.
A processing pattern that traverses a sequence and accumulates the elements into a single result.
A processing pattern that traverses a sequence and performs an operation on each element.
Something a variable can refer to. An object has a type and a value.
Having the same value.
Being the same object (which implies equivalence).
The association between a variable and its value.
A circumstance where two or more variables refer to the same object.
A character or string used to indicate where a string should be split.
Write a function called nested_sum
that takes a list of lists
of integers and adds up the elements from all of the nested lists.
For example:
Write a function called cumsum that takes a list of numbers and returns the cumulative sum; that is, a new list where the th element is the sum of the first elements from the original list. For example:
Write a function called middle
that takes a list and
returns a new list that contains all but the first and last
elements. For example:
Write a function called chop
that takes a list, modifies it
by removing the first and last elements, and returns None.
For example:
Write a function called is_sorted
that takes a list as a
parameter and returns True if the list is sorted in ascending
order and False otherwise. For example:
Two words are anagrams if you can rearrange the letters from one
to spell the other. Write a function called is_anagram
that takes two strings and returns True if they are anagrams.
Write a function called has_duplicates
that takes
a list and returns True if there is any element that
appears more than once. It should not modify the original
list.
This exercise pertains to the so-called Birthday Paradox, which you can read about at http://en.wikipedia.org/wiki/Birthday_paradox.
If there are 23 students in your class, what are the chances that two of them have the same birthday? You can estimate this probability by generating random samples of 23 birthdays and checking for matches. Hint: you can generate random birthdays with the randint function in the random module.
Write a function that reads the file words.txt and builds a list with one element per word. Write two versions of this function, one using the append method and the other using the idiom t = t + [x]. Which one takes longer to run? Why?
To check whether a word is in the word list, you could use the in operator, but it would be slow because it searches through the words in order.
Because the words are in alphabetical order, we can speed things up with a bisection search (also known as binary search), which is similar to what you do when you look a word up in the dictionary (the book, not the data structure). You start in the middle and check to see whether the word you are looking for comes before the word in the middle of the list. If so, you search the first half of the list the same way. Otherwise you search the second half.
Either way, you cut the remaining search space in half. If the word list has 113,809 words, it will take about 17 steps to find the word or conclude that it’s not there.
Write a function called in_bisect
that takes a sorted list
and a target value and returns True if the word is
in the list and False if it’s not.
Or you could read the documentation of the bisect module and use that!
Two words are a “reverse pair” if each is the reverse of the other. Write a program that finds all the reverse pairs in the word list.
Two words “interlock” if taking alternating letters from each forms a new word. For example, “shoe” and “cold” interlock to form “schooled”. Credit: This exercise is inspired by an example at http://puzzlers.org.
Write a program that finds all pairs of words that interlock. Hint: don’t enumerate all pairs!
Can you find any words that are three-way interlocked; that is, every third letter forms a word, starting from the first, second or third?