Take a look at the three different "lists" below, guess the outputs:
(a)
>>> lists = [ [], [], [] ]
>>> lists
[[], [], []]
>>> lists[1].append("Hi there!")
>>> lists
?
(b)
>>> lists = [ [] for i in range(3) ]
>>> lists
[[], [], []]
>>> lists[1].append("Hi there!")
>>> lists
?
(c)
>>> lists = [ [] * 3 ]
>>> lists
[[], [], []]
>>> lists[1].append("Hi there!")
>>> lists
?
All same? Yeah, I do agree with you. However, here are what we actually get:
(a)
[[], ['Hi there!'], []]
(b)
[[], ['Hi there!'], []]
(c)
[['Hi there!'], ['Hi there!'], ['Hi there!']]
What has happened is that [[]]
is a one-element list containing an empty list, so all three elements of [[]] * 3
are (pointers to) this single empty list. Modifying any of the elements of lists
modifies this single list.
See more at Chapter 3.6 - Sequence Types, Python Library Reference .