Writing structured program (4.1)

As I could not see the end of the exercises of Chapter 3, I decided to continue Chapter 4 of the whale book.

Now, Go back to basic (chapter 4.1)

>>> foo = "Monty"
>>> bar = foo
>>> foo = "Python"
>>> bar
'Monty'
>>> foo
'Python'

I have seen similar one in some other books.

>>> foo = ['Monty', 'Python']
>>> bar = foo
>>> foo[1] = 'Bodkin'
>>> bar
['Monty', 'Bodkin']
>>> 

How do I understand this?

>>> empty = []
>>> nested = [empty, empty, empty]
>>> nested
[[], [], []]
>>> nested[1].append('Python')
>>> nested
[['Python'], ['Python'], ['Python']]
>>> empty
['Python']

nested[1] refers to empty. This means the value of empty is updated with 'Python'.

>>> nested = [[]] * 3
>>> nested[1].append('Shanghai')
>>> nested
[['Shanghai'], ['Shanghai'], ['Shanghai']]
>>> id(nested[0])
4347110320
>>> id(nested[1])
4347110320
>>> id(nested[2])
4347110320

This means they are all the same list. I saw different behavior in this example.

>>> nested = [[]] * 3
>>> nested
[[], [], []]
>>> empty
['Python']
>>> nested[1] = 'Shanghai'
>>> nested
[[], 'Shanghai', []]

In this case, I just made a mistake and directly put the value instead of using append(). As a result, other elements were not updated. We can see completely same situation in the text book.

>>> nested = [[]] * 3
>>> nested[1].append('Shanghai')
>>> nested[1] = ['Hong Kong']
>>> nested
[['Shanghai'], ['Hong Kong'], ['Shanghai']]
>>> 

Usage of '==' and 'is'. What is difference?

>>> size = 5
>>> python = ['python']
>>> snake_nest = [python] * size
>>> snake_nest[0] == snake_nest[1] == snake_nest[2] == snake_nest[3] == snake_nest[4]
True
>>> snake_nest[0] is snake_nest[1] is snake_nest[2] is snake_nest[3] is snake_nest[4]
True
>>>

No difference?

>>> import random
>>> position = random.choice(range(size))
>>> snake_nest[position] = ['python']
>>> snake_nest
[['python'], ['python'], ['python'], ['python'], ['python']]
>>> snake_nest[0] == snake_nest[1] == snake_nest[2] == snake_nest[3] == snake_nest[4]
True
>>> snake_nest[0] is snake_nest[1] is snake_nest[2] is snake_nest[3] is snake_nest[4]
False
>>> position
3
>>> [id(snake) for snake in snake_nest]
[4347112192, 4347112192, 4347112192, 4347110176, 4347112192]
>>> snake_nest[0] is snake_nest[1] is snake_nest[2] is snake_nest[4] 
True
>>>  

According to the result above, '==' is comparing the value itself. On the other hand, 'is' to compare id.

Regarding conditions, if/elif/else is the python's format.

>>> animals = ['cat', 'dog']
>>> if 'cat' in animals:
...     print 1
... elif 'dog' in animals:
...     print 2
... 
1
>>> if 'cat' in animals:
...     print 1
... 
1
>>> if 'dog' in animals:
...     print 2
... 
2

all/any are new for me.

>>> sent = ['No', 'good', 'fish', 'goes', 'anywhere', 'without', 'a', 'porpoise', '.']
>>> all(len(w) > 4 for w in sent)
False
>>> any(len(w) > 4 for w in sent)
True
>>>