Booleans in Python
not
in Python:
>>> not True
False
>>> not False
True
or
in Python:
>>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False
and
in Python:
>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False and False
False
Lists
Making a new empty list.
>>> x = []
Let's add some items.
>>> x.append("cows")
>>> x
['cows']
>>> x.append("sheep")
>>> x
['cows', 'sheep']
>>> x.append(42)
>>> x
['cows', 'sheep', 42]
Lists are heterogeneous. They can even contain other lists.
>>> x.append([1,2,3,4])
>>> x
['cows', 'sheep', 42, [1, 2, 3, 4]]
Now we play some indexing games.
>>> x[0]
'cows'
>>> x[3].append(["cats", "dawgs", "elliefants"])
>>> x
['cows', 'sheep', 42, [1, 2, 3, 4, ['cats', 'dawgs', 'elliefants']]]
>>> x[0]
'cows'
>>> x[0][0]
'c'
>>> x[3]
[1, 2, 3, 4, ['cats', 'dawgs', 'elliefants']]
>>> x[3][4]
['cats', 'dawgs', 'elliefants']
>>> x[3][4][2]
'elliefants'
>>> x[3][4][2][0]
'e'
Casting a string to a list explodes it into a list of characters.
>>> list("trinitrotolulene")
['t', 'r', 'i', 'n', 'i', 't', 'r', 'o', 't', 'o', 'l', 'u', 'l', 'e', 'n', 'e']
Humpty Dumpty can be glued back together again. Notice that
join
was called on a string. It's a string method that
takes a list as an argument.
>>> smithereens = list("trinitrotolulene") >>> "".join(smithereens) 'trinitrotolulene'
Let's go shoppping!
>>> shopping = [] >>> shopping.append("steak") >>> shopping.append("broccoli") >>> shopping.append("chocolate milk") >>> shopping ['steak', 'broccoli', 'chocolate milk']
The
len
function tells you the number of items in a list, as well as the length of a string.>>> len(shopping) 3
The
in
keyword checks for membership.>>> "milk" in shopping False >>> shopping.append("milk")
Note how
in
works on strings.>>> "cow" in "cowabunga" True
Mutability It's convenient and dangerous. All of the scalar types, int, string and boolean are immutable objects. Once created in memory, they cannot be changed.
Lists are different. They aer mutable. The state of a list is the objects in it and their association to the indices (order).
You are about to see a mutability pitfall, aliasing.
>>> x = [1,2,3] >>> y = x >>> y [1, 2, 3] >>> x [1, 2, 3] >>> y[0] = 5 >>> y [5, 2, 3] >>> x [5, 2, 3]
Notice that every Python object has an ID, which is its memory address.
>>> id(x) 140363846671296 >>> id(y) 140363846671296 >>> id(0) 4462098752 >>> id(1) 4462098784 >>> id(2) 4462098816 >>> id(3) 4462098848 >>> id(5) 4462098912 >>> id(100) - id(0) 3200 >>> id(200) - id(0) 6400 >>> id(300) - id(0) 140359387297968 >>>