8 September 2020

Lists

Last Time We discussed lists. List indices function like string indices do.

>>> x = [2,3,4,5,True,"cat"]
>>> x[0]
2

These exist.

>>> x[-1]
'cat'
>>> x[-2]
True

This is a very common Python idiom (clip off last item in a sequence).

>>> x = x[:-1]
>>> x
[2, 3, 4, 5, True]

You can slice lists like you do strings.

>>> x[1:3]
[3, 4]

List slices are lvalues that can store lists.

>>> x[1:3] = ["A", "B", "C"]
>>> x
[2, 'A', 'B', 'C', 5, True]

In this situation, a string is cast to a list implicitly.

>>> x[1:1] = "dawg"
>>> x
[2, 'd', 'a', 'w', 'g', 'A', 'B', 'C', 5, True]

This is a no-no.

>>> x[::2] = []
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 0 to extended slice of size 5

But you can do this.

>>> x[::2] = 9,8,7,6,5
>>> x
[9, 'd', 8, 'w', 7, 'A', 6, 'C', 5, True]

Now suppose we do this and want to swap the two values.

>>> x = 0
>>> y = 1

You can do this.

>>> tmp = x
>>> x = y
>>> y = tmp
>>> x
1
>>> y
0

But this is quicker and clearer.

>>> x,y = y,x
>>> x
0
>>> y
1

Now watch this.

>>> x = ["Ethan", "Messier", "is", "nuts"]
>>> x[0], x[1] = x[1], x[0]
>>> x
['Messier', 'Ethan', 'is', 'nuts']

This is called "unpacking."

>>> one, two, three, four = x
>>> one
'Messier'
>>> two
'Ethan'
>>> three
'is'
>>> four
'nuts'

Here Python will send you packing with a hiss.

>>> one, two, three, four, five = x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 5, got 4)

Also, we see the list type.

>>> type(x)
<class 'list'>

Tuples

Tuples are immutable lists. Here we make a tuple and do some familar things with the predictable results.

>>> t = (1,2,3,4,5)
>>> type(t)
<class 'tuple'>
>>> t[0]
1
>>> t[1:3]
(2, 3)
>>> (1,2,3) + (4,5,6)
(1, 2, 3, 4, 5, 6)

Here we try to violate immutability.

>>> t[0] = "hippopotamus"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Watch this.

>>> s = (1,2,3)
>>> t = (4,5,6)
>>> s + t
(1, 2, 3, 4, 5, 6)
>>> u = s
>>> u is s
True
>>> s += t
>>> s
(1, 2, 3, 4, 5, 6)
>>> u is s
False

The line s += t triggered the making of a new tuple, because tuples are immutable. Let us repeat this for a list.

>>> s = [1,2,3]
>>> t = [4,5,6]
>>> u = s
>>> s += t
>>> u is s
True

No new list got created; t just gets tacked onto the existing list.

Remember this: The state for any sequeence consists of the items present and the order of items within the collection.

Go to work on boolean.html.