Lesson 6, Bit 2: Lists and Strings

A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use list:

Code Output
s = 'spam'

t = list[s]

print(t)
['s', 'p', 'a', 'm']

Because list is the name of a built-in function, you should avoid using it as a variable name. I also avoid the letter l because it looks too much like the number 1. So that's why I use t.

The list function breaks a string into individual letters. If you want to break a string into words, you can use the split method:

Code Output
s = 'pining for the fjords'

t = s.split()

print(t)
['pining', 'for', 'the', 'fjords']

Once you have used split to break the string into a list of words, you can use the index operator (square bracket) to look at a particular word in the list.

Code Output
print(t[2]) the

You can call split with an optional argument called a delimiter that specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter:

Code Output
s = 'spam-spam-spam'

t = s.split('-')

print(t)
['spam', 'spam', 'spam']

Join

join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:

Code Result
t = ['pining', 'for', 'the', 'fjords']

delimiter = ' '

delimiter.join(t)
pining for the fjords

In this case the delimiter is a space character, so join puts a space between words. To concatenate strings without spaces, you can use the empty string, ", as a delimiter.

Aliasing

If a refers to an object and you assign b = a, then both variables refer to the same object:

Code Result
a = [1, 2, 3]

b = a

b is a
True

The association of a variable with an object is called a reference. In this example, there are two references to the same object: both a and b point to the same list.

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:

Code Output
a = [1, 2, 3]

b = a

b[0] = 17

print(a)
print(b)
[17, 2, 3]
[17, 2, 3]

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:

Code Output
a = 'banana'

b = a

b = 'apple'

print(a)
print(b)
banana
apple

It almost never makes a difference whether a and b refer to the same string or not.

List Arguments

When you pass a list to a function, the function gets a reference to the list. If the function modifies a list parameter, the caller sees the change. For example, delete_head removes the first element from a list:

def delete_head(t):
    del t[0]

Here's how it is used:

Code Output
letters = ['a', 'b', 'c']

delete_head(letters)

print(letters)
['b', 'c']

The parameter t and the variable letters are aliases for the same object.

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:

Code Output
t1 = [1, 2]

t2 = t1.append(3)

print(t1)
[1, 2, 3]
print(t2) None
t3 = t1 + [3]

print(t3)
[1, 2, 3]
t2 is t3 False

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:

def bad_delete_head(t):
    t = t[1:]              # WRONG!

The slice operator (:) creates a new list and the assignment makes t refer to it, but none of that has any effect on the list that was passed as an argument.

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:

def tail(t):
    return t[1:]

This function leaves the original list unmodified. Here's how it is used:

Code Output
letters = ['a', 'b', 'c']

rest = tail(letters)

print(rest)
['b', 'c']

Debugging Lists

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:

1. Don't forget that 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:

word = word.strip()

It is tempting to write list code like this:

t = t.sort()           # WRONG!

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.

2. Pick an idiom and stick with it.

Part of the problem with lists is that there are too many ways to do things. For example, to remove an element from a list, you can use pop, remove, del, or even a slice assignment.

To add an element, you can use the append method or the + operator. But don't forget that these are right:

t.append(x)
t = t + [x]

And these are wrong:

t.append([x])          # WRONG!
t = t.append(x)        # WRONG!
t + [x]                # WRONG!
t = t + x              # WRONG!

Try out each of these examples in interactive mode to make sure you understand what they do. Notice that only the last one causes a runtime error; the other three are legal, but they do the wrong thing.

3. 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.

orig = t[:]
t.sort()

In this example you could also use the built-in function sorted, which returns a new, sorted list and leaves the original alone. But in that case you should avoid using sorted as a variable name!