Amusing Python 1: "*"
Take a look at the three different "lists" below, guess the outputs:(a)
>>> lists = [ [], [], [] ]
>>> lists
[[], [], []]
>>> lists.append("Hi there!")
>>> lists
?
(b)
>>> lists = [ [] for i in range(3) ]
>>> lists
[[], [], []]
>>> lists.append("Hi there!")
>>> lists
?
(c)
>>> lists = [ [] * 3 ]
>>> lists
[[], [], []]
>>> lists.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 containingan empty list, so all three elements of [[]] * 3are (pointers to)this single empty list.Modifying any of the elements of listsmodifies this single list.
See more at
Chapter 3.6
- Sequence Types,
Python Library Reference
.
页:
[1]