The Difference Between Lists and Strings

Strings and lists are both kinds of sequence. We can pull them apart by indexing and slicing them, and we can join them together by concatenating them. However, we cannot join strings and lists: >>> query = 'Who knows?'

>>> beatles = ['John', 'Paul', 'George', 'Ringo']

>>> beatles[2] 'George' >>> query[:2] 'Wh'

"Who knows? I don't"

Traceback (most recent call last):

File "<stdin>", line 1, in <module> TypeError: can only concatenate list (not "str") to list >>> beatles + ['Brian']

When we open a file for reading into a Python program, we get a string corresponding to the contents of the whole file. If we use a for loop to process the elements of this string, all we can pick out are the individual characters—we don't get to choose the granularity. By contrast, the elements of a list can be as big or small as we like: for example, they could be paragraphs, sentences, phrases, words, characters. So lists have the advantage that we can be flexible about the elements they contain, and correspondingly flexible about any downstream processing. Consequently, one of the first things we are likely to do in a piece of NLP code is tokenize a string into a list of strings (Section 3.7). Conversely, when we want to write our results to a file, or to a terminal, we will usually format them as a string (Section 3.9).

Lists and strings do not have exactly the same functionality. Lists have the added power that you can change their elements:

>>> beatles[0] = "John Lennon" >>> del beatles[-l] >>> beatles

On the other hand, if we try to do that with a string—changing the 0th character in query to 'F'—we get:

Traceback (most recent call last):

File "<stdin>", line 1, in ? TypeError: object does not support item assignment

This is because strings are immutable: you can't change a string once you have created it. However, lists are mutable, and their contents can be modified at any time. As a result, lists support operations that modify the original value rather than producing a new value.

Your Turn: Consolidate your knowledge of strings by trying some of the exercises on strings at the end of this chapter.

Was this article helpful?

0 0

Post a comment