Text
stringlengths
1
9.41k
These are fundamental data structures that can be used to store, retrieve, and, in some contexts, manipulate data.
We sometimes refer to these as “sequences” since they carry with them the concepts of order and sequence. Strings (str) are also sequences. **Learning objectives** - You will learn about lists, and about common list operations, including adding and removing elements, finding the number of elements in a list, checki...
This means that you can modify a list after it’s created. We can append items, remove items, change the values of individual items and more. - You will learn about tuples.
Tuples are unlike lists in that they are immutable—they cannot be changed. - You will learn that strings are sequences. - You will learn how to use indices to retrieve individual values from these structures. In the next chapter, we’ll learn how to iterate over the elements of a sequence. **Terms introduced** ...
One could not enumerate all possible applications of lists.[1] Lists are ubiquitous, and you’ll see they come in handy! ###### What is a list? A list is a mutable sequence of objects.
That sounds like a mouthful, but it’s not that complicated. If something is mutable, that means that it can change (as opposed to immutable, which means it cannot).
A sequence is an ordered collection—that is, each element in the collection has its own place in some ordering. For example, we might represent customers queued up in a coffee shop with a list.
The list can change—new people can get in the coffee shop queue, and the people at the front of the queue are served and they leave. So the queue at the coffee shop is mutable.
It’s also ordered—each customer has a place in the queue, and we could assign a number to each position.
This is known as an index. ###### How to write a list in Python The syntax for writing a list in Python is simple: we include the objects we want in our list within square brackets.
Here are some examples of lists: ``` coffee_shop_queue = ['Bob', 'Egbert', 'Jason', 'Lisa', 'Jim', 'Jackie', 'Sami'] scores = [74, 82, 78, 99, 83, 91, 77, 98, 74, 87] ``` We separate elements in a list with commas. Unlike many other languages, the elements of a Python list needn’t all be of the same...
So this is a perfectly valid list: ``` mixed = ['cheese', 0.1, 5, True] ``` There are other ways of creating lists in Python, but this will suffice for now. At the Python shell, we can display a list by giving its name. ``` >>> mixed = ['cheese', 0.1, 5, True] >>> mixed ['cheese', 0.1, 5, True] ``` 1If you’ve...
Yup, and we call that the _empty list._ ``` >>> aint_nothing_here = [] >>> aint_nothing_here [] ###### Accessing individual elements in a list ``` As noted above, lists are ordered.
This allows us to access individual elements within a list using an index. An index is just a number that corresponds to an element’s position within a list.
The only twist is that in Python, and most programming languages, indices start with zero rather than one.[2] So the first element in a list has index 0, the second has index 1, and so on.
Given a list of 𝑛 elements, the indices into the list will be integers in the interval [0, 𝑛−1]. **Figure 10.1: A list and its indices** In the figure (above) we depict a list of floats of size eleven—that is, there are eleven elements in the list.
Indices are shown below the list, with each index value associated with a given element in the list.
Notice that with a list of eleven elements, indices are integers in the interval [0, 10]. Let’s turn this into a concrete example: ``` >>> data = [4.2, 9.5, 1.1, 3.1, 2.9, 8.5, 7.2, 3.5, 1.4, 1.9, 3.3] ``` Now let’s access individual elements of the list.
For this, we give the name of the list followed immediately by the index enclosed in brackets: ``` >>> data[0] 4.2 ``` The element in the list data, at index 0, has a value of 4.2.
We can access other elements similarly. 2Some languages are one-indexed, meaning that their indices start at one, but these are in the minority.
One-indexed languages include Cobol, Fortran, Julia, Matlab, R, and Lua. ----- ``` >>> data[1] 9.5 >>> data[9] 1.9 IndexError ``` Let’s say we have a list with 𝑛 elements.
What happens if we try to access a list using an index that doesn’t exist, say index 𝑛 or index 𝑛+ 1? ``` >>> foo = [2, 4, 6] >>> foo[3] # there is no element at index 3!!! Traceback (most recent call last): File "/.../code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <...
To do this, we put the list and index on the left side of an assignment. ``` >>> data [4.2, 9.5, 1.1, 3.1, 2.9, 8.5, 7.2, 3.5, 1.4, 1.9, 3.3] >>> data[7] = 6.1 >>> data [4.2, 9.5, 1.1, 3.1, 2.9, 8.5, 7.2, 6.1, 1.4, 1.9, 3.3] ``` Let’s do another: We’ll change the element at index 2 to 4.7. ``` >>> data[2] ...
Here are a few such built-in functions: ----- description constraint(s) if any example `sum()` calculates sum of values must be numeric or `sum(data)` elements Boolean * `len()` returns number of none `len(data)` elements `max()` returns largest can’t mix numerics and `max(data)` value strings; must be all numer...
If the list contains only numeric values, the answer is “yes,” but Python doesn’t supply a built-in for this.
However, the solution is straightforward. ``` >>> sum(data) / len(data) 4.8 ``` … and there’s our mean! ###### Some convenient list methods We’ve seen already that string objects have methods associated with them.
For example, .upper(), .lower(), and .capitalize().
Recall that methods are just functions associated with objects of a given type, which operate on the object’s data (value or values). Lists also have handy methods which operate on a list’s data.
Here are a few: ----- description constraint(s) if any example `.sort()` sorts list can’t mix strings `data.sort()` and numerics `.append()` appends an item to list none `data.append(8)` `.pop()` “pops” the last cannot pop from `data.pop()` element off list empty list and returns its value _or_ removes the eleme...
If we call .pop() without an argument, Python will remove the last element in the list and return its value. ``` >>> data.pop() 5.9 >>> data [4.2, 9.5, 4.7, 3.1, 2.9, 8.5, 7.2, 6.1, 1.4, 1.9, 3.3] ``` Notice that the value 5.9 is returned, and that the last element in the list (5.9) has been removed. Sometimes...
For this we can supply an index, .pop(i), where i is the index of the element we wish to pop. ``` >>> data.pop(1) 9.5 ``` ----- ``` >>> data [4.2, 4.7, 3.1, 2.9, 8.5, 7.2, 6.1, 1.4, 1.9, 3.3] ``` For reasons which may be obvious, we cannot .pop() from an empty list, and we cannot .pop(i) if the index i does...
In place means that the list is modified right where it is, and there’s no list returned from .sort().
This means that calling .sort() alters the list! ``` >>> data [4.2, 4.7, 3.1, 2.9, 8.5, 7.2, 6.1, 1.4, 1.9, 3.3] >>> data.sort() >>> data [1.4, 1.9, 2.9, 3.1, 3.3, 4.2, 4.7, 6.1, 7.2, 8.5] ``` This is unlike the string methods like .lower() which return an altered _copy of the string.
Why is this? Strings are immutable; lists are mutable._ Because .sort() sorts a list in place, it returns None.
So don’t think you can work with the return value of .sort() because there isn’t any! Example: ``` >>> m = [5, 7, 1, 3, 8, 2] >>> n = m.sort() >>> n >>> type(n) <class 'NoneType'> ###### Some things you might not expect ``` Lists behave differently from many other objects when performing assignment.
Let’s say you wanted to preserve your data “as-is” but also have a sorted version.
You might think that this would do the trick. ``` >>> data = [4.2, 4.7, 3.1, 2.9, 8.5, 7.2, 6.1, 1.4, 1.9, 3.3] >>> copy_of_data = data # naively thinking you're making a copy >>> data.sort() >>> data [1.4, 1.9, 2.9, 3.1, 3.3, 4.2, 4.7, 6.1, 7.2, 8.5] ``` But now look what happens when we inspect copy_of_dat...
What? How did that happen? ----- When we made the assignment copy_of_data = data we assumed (quite reasonably) that we were making a copy of our data. It turns out this is not so.
What we wound up with was two names for the same underlying _data structure, data and copy_of_data.
This is the way things work with_ mutable objects (like lists).[3] So how do we get a copy of our list?
One way is to use the .copy() method.[4] This will return a copy of the list, so we have two different list instances.[5] ``` >>> data = [4.2, 4.7, 3.1, 2.9, 8.5, 7.2, 6.1, 1.4, 1.9, 3.3] >>> copy_of_data = data.copy() # call the copy method >>> data.sort() >>> data [1.4, 1.9, 2.9, 3.1, 3.3, 4.2, 4.7, 6.1, 7....
How might we go about it? We could take a brute force approach. Say our list is called x. ``` >>> x[len(x) - 1] ``` Let’s unpack that. Within the brackets we have the expression len(x) ``` - 1.
len(x) returns the number of elements in the list, and then we ``` subtract 1 to adjust for zero-indexing (if we have 𝑛 elements in a list, the index of the last element is 𝑛−1).
So that works, but it’s a little clunky.
Fortunately, Python allows us to get the last element of a list with an index of -1. ``` >>> x[-1] ``` You may think of this as counting backward through the indices of the list. ###### A puzzle (optional) Say we have some list x (as above), and we’re intrigued by this idea of counting backward through a list, and...
However, [if you’re curious, see: https://docs.python.org/3/library/copy.html.](https://docs.python.org/3/library/copy.html) 4There are other approaches to creating a copy of a list, specifically using the list constructor or slicing with [:], but we’ll leave these for another time.
However, slicing is slower than the other two. Source: I timed it. [5Actually it makes what’s called a shallow copy.
See: https://docs.python.org/](https://docs.python.org/3/library/copy.html) [3/library/copy.html.](https://docs.python.org/3/library/copy.html) ----- index. Is this possible?
Can you write a solution that works for any list ``` x? ###### 10.2 Tuples ``` A tuple? What’s a tuple?
A tuple is an immutable sequence of objects. Like lists they allow for indexed access of elements. Like lists they may contain any arbitrary type of Python object (int, float, bool, str, _etc.).
Unlike lists they are immutable, meaning that once created they_ cannot change.
You’ll see that this property can be desirable in certain contexts. ###### How do we write a tuple? The crucial thing in writing a tuple is commas—we separate elements of a tuple with commas—but it’s conventional to write them with parentheses as well. Here are some examples: ``` >>> coordinates = 0.378, 0.911 >>...
Lists are a dynamic data structure. Tuples on the other hand are well-suited to static data. As one example, say we’re doing some geospatial tracking or analysis.
We might use tuples to hold the coordinates of some location—the latitude and longitude.
A tuple is appropriate in this case. ``` >>> (44.4783021, -73.1985849) ``` Clearly a list is not appropriate: we’d never want to append elements or remove elements from latitude and longitude, and coordinates like this belong together—they form a pair. Another case would be records retrieved from some kind of databa...
3.21, 'sophomore') ``` Another reason that tuples are preferred in many contexts is that creating a tuple is more efficient than creating a list.
So, for example, if you’re reading many records from a database into Python objects, using ----- tuples will be faster.
However, the difference is small, and could only become a factor if handling many records (think millions). ###### You say tuples are immutable. Prove it. Just try modifying a tuple.
Say we have the tuple (1, 2, 3). We can read individual elements from the tuple just like we can for lists.
But unlike lists we can’t use the same approach to assign a new value to an element of the tuple. ``` >>> t = (1, 2, 3) >>> t[0] 1 >>> t[0] = 51 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment ``` There you have it: “ ‘tup...
What’s happened here is that you’ve created a new tuple, and given it the same name t. **What about a tuple that contains a list?** Tuples can contain any type of Python object—even lists.
This is valid: ``` >>> t = ([1, 2, 3],) >>> t ([1, 2, 3],) ``` Now let’s modify the list. ``` >>> t[0][0] = 5 >>> t ([5, 2, 3],) ``` Haven’t we just modified the tuple? Actually, no.
The tuple contains the list (which is mutable).
So we can modify the list within the tuple, but we can’t replace the list with another list. ----- ``` >>> t = ([1, 2, 3],) >>> new_list = [4, 5, 6] >>> t[0] = new_list Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment ``` ...
The list has an index within the tuple, and the elements of the list have their indices within the list.
So the first index is used to retrieve the list from within the tuple, and the second is used to retrieve the element from the list. ``` >>> t = (['a', 'b', 'c'],) >>> t[0] ['a', 'b', 'c'] >>> t[0][0] 'a' >>> t[0][1] 'b' >>> t[0][2] 'c' ###### 10.3 Mutability and immutability ``` Mutability and immu...
Later, we’ll see another mutable data structure, the dictionary. ###### Immutable objects You may ask what’s been happening in cases like this: ``` >>> x = 75021 >>> x 75021 >>> x = 61995 >>> x 61995 ``` Aren’t we changing the value of x?
While we might speak this way casually, what’s really going on here is that we’re creating a new int, x. ----- Here’s how we can demonstrate this—using Python’s built-in function ``` id().[6] >>> x = 75021 >>> id(x) 4386586928 >>> x = 61995 >>> id(x) 4386586960 ``` See?
The IDs have changed. The IDs you’ll see if you try this on your computer will no doubt be different.
But you get the idea: different IDs mean we have two different objects! Same goes for strings, another immutable type. ``` >>> s = 'Pharoah Sanders' # who passed away the day I wrote this >>> id(s) 4412581232 >>> s = 'Sal Nistico' >>> id(s) 4412574640 ``` Same goes for tuples, another immutable type. ``` ...
Lists are mutable. 6While using id() is fine for tinkering around in the Python shell, this is the only place it should be used. Never include id() in any programs you write.
The Python documentation states that id() returns “the ‘identity’ of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime.
Two objects with non-overlapping lifetimes may have the same id() value.” So please keep this in mind. ----- ``` >>> parts = ['rim', 'hub', 'spokes'] >>> id(parts) 4412569472 >>> parts.append('inner tube') >>> parts ['rim', 'hub', 'spokes', 'inner tube'] >>> id(parts) 4412569472 >>> parts.pop(0) ...
We make changes to the list and the ID remains unchanged.
It’s the same object throughout! ###### Variables, names, and mutability Assignment in Python is all about names, and it’s important to understand that when we make assignments we are not copying values from one variable to another.
This becomes most clear when we examine the behavior with respect to mutable objects (for example, lists): ``` >>> lst_a = [1, 2, 3, 4, 5] >>> lst_b = lst_a ``` Now let’s change lst_a. ``` >>> lst_a.append(6) >>> lst_b [1, 2, 3, 4, 5, 6] ``` See?
lst_b isn’t a copy of lst_a, it’s a different name for the same object! If a mutable value has more than one name, if we affect some change in the value via one name, all the other names still refer to the mutated value. Now, what do you think about this example: ``` >>> lst_a = [1, 2, 3, 4, 5] >>> lst_b = [1, 2, 3...
Or do they refer to different objects? ----- ``` >>> lst_a [1, 2, 3, 4, 5, 6] >>> lst_b [1, 2, 3, 4, 5] lst_a and lst_b are names for different objects!
Now, does this mean ``` that assignment works differently for mutable and immutable objects? Not at all. Then why, you may ask, when we assign 1 to x and 1 to y do both names refer to the same value, whereas when we assign [1, 2, 3, 4, 5] to lst_a and [1, 2, 3, 4, 5] to lst_b we have two different lists? Let’s say you...
Furthermore, let’s say your lists were identical… **Trigger warning: opinions about MLB teams follow!** ``` >>> my_list = ['Cubs', 'Tigers', 'Dodgers'] >>> janes_list = ['Cubs', 'Tigers', 'Dodgers'] ``` Now, my list is my list, and Jane’s list is Jane’s list.
These are two different lists. Let’s say that the Dodgers fell out of favor with Jane, and she replaced them with the Cardinals (abhorrent, yes, I know). ``` >>> janes_list.pop() 'Dodgers' >>> janes_list.append('Cardinals') >>> janes_list ['Cubs', 'Tigers', 'Cardinals'] >>> my_list ['Cubs', 'Tigers', 'Dod...
Even though the lists started with identical elements, they’re still two different lists and mutating one does not mutate the other. But be aware that we can give two different names to the same mutable object (as shown above). ``` >>> lst_a = [1, 2, 3, 4, 5] >>> lst_b = lst_a >>> lst_a.append(6) >>> lst_a [1...
We may think we’re making a copy of the list, when in fact, we’re only giving it another name.
This can result in unexpected behavior—we think we’re ----- modifying a copy of a list, when we’re actually modifying the list under another name! ###### 10.4 Subscripts are indices Here we make explicit the connection between subscript notation in mathematics and indices in Python. In mathematics: Say we have a c...
We can refer to individual elements of the collection by associating each element of the collection with some index from the natural numbers.
Thus, 𝑥0 ∈𝑋 𝑥1 ∈𝑋 … 𝑥𝑛 ∈𝑋 Different texts may use different starting indices. For example, a linear algebra text probably starts indices at one.
A text on set theory is likely to use indices starting at zero. In Python, sequences—lists, tuples, and strings—are indexed in this fashion.
All Python indices start at zero, and we refer to Python as being _zero indexed._ Indexing works the same for lists, tuples, and even strings.
Remember that these are sequences—ordered collections—so each element has an index, and we may access elements within the sequence by its index. ``` my_list = ['P', 'O', 'R', 'C', 'U', 'P', 'I', 'N', 'E'] ``` We start indices at zero, and for a list of length 𝑛, the indices range from zero to 𝑛−1. It’s exactly the...
That’s because it is!
It’s even the same for strings. ``` my_string = 'PORCUPINE' ``` ----- While we don’t explicitly separate the characters of a string with commas, they are a sequence nonetheless, and we can read characters by index. ###### 10.5 Concatenating lists and tuples Sometimes we have two or more lists or tuples, and we w...
We’ve already seen how we can concatenate strings using the + operator.
This works for lists and tuples too! ``` >>> plain_colors = ['red', 'green', 'blue', 'yellow'] >>> fancy_colors = ['ultramarine', 'ochre', 'indigo', 'viridian'] >>> all_colors = plain_colors + fancy_colors >>> all_colors ['red', 'green', 'blue', 'yellow', 'ultramarine', 'ochre', 'indigo', 'viridian'] ``` ...
Coupling two trains with multiple cars preserves the ordering of the cars. Answering the inevitable question: Can we concatenate a list with a tuple using the + operator?
No, we cannot. ``` >>> [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] >>> [1, 2, 3] + (4, 5, 6) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate list (not "tuple") to list ###### 10.6 Copying lists ``` We’ve seen elsewhere that the following simply gives an...
The ``` .copy() method returns a shallow copy of a list. >>> lst_1 = ['gamma', 'epsilon', 'delta', 'alpha', 'beta'] >>> lst_2 = lst_1.copy() >>> lst_1.sort() >>> lst_2 ['gamma', 'epsilon', 'delta', 'alpha', 'beta'] ``` We can copy a list using a slice. ``` >>> lst_1 = ['gamma', 'epsilon', 'delta', 'alpha',...
The list constructor takes some iterable and iterates it, producing a new list composed of the elements yielded by iteration.
Since lists are iterable, we can use this to create a copy of a list. ``` >>> lst_1 = ['gamma', 'epsilon', 'delta', 'alpha', 'beta'] >>> lst_2 = list(lst_1) # using the list constructor >>> lst_1.sort() >>> lst_2 ['gamma', 'epsilon', 'delta', 'alpha', 'beta'] ``` So now we have three ways to make a copy of a...
Sometimes we also want to find the index of the element within a sequence.
Python makes this relatively straightforward. ----- ###### Checking to see if an element is in a sequence Say we have the following list: ``` >>> fruits = ['kumquat', 'papaya', 'kiwi', 'lemon', 'lychee'] ``` We can check to see if an element exists using the Python keyword in. ``` >>> 'kiwi' in fruits True ...