List of lists in python
Created a list of lists by using multiply symbol:
>>> a = [[]] * 2 >>> a [[], []] >>> a[0].append('hello') >>> a [['hello'], ['hello']]
It’s weird that adding one item to first list have side-effect on second list! Seems ‘* 2’ makes two reference for one list.
How to avoid this then? The answer is using normal syntax:
>>> a = [[], []] >>> a [[], []] >>> a[0].append('hello') >>> a [['hello'], []] >>>
A difference between python2 and python3
There are many trivial differences between python3 and python3, and I luckily found one this week:
# In python2 >>> dict = {1: 'hello', 2: 'world'} >>> dict.values() ['hello', 'world'] # In python3 >>> dict = {1: 'hello', 2: 'world'} >>> dict.values() dict_values(['hello', 'world'])
In python3, the values() of a dictionary is not type of ‘list’ but ‘dict_values’. To be compatible to python2, we need to add
list(dict.values())
for old python2 codes.