[Tutor] difference between [[], [], []] and 3*[[]]
Kent Johnson
kent37 at tds.net
Sat May 21 16:01:14 CEST 2005
Mitsuo Hashimoto wrote:
> Hello,
>
> What's the difference between "[[], [], []]" and "3*[[]]" ?
[[], [], []] makes a list containing references to three different lists.
3*[[]] makes a list with three references to the *same* list. This can cause surprising behavior:
>>> l=3*[[]]
>>> l
[[], [], []]
>>> l[0].append(1)
>>> l
[[1], [1], [1]]
Because each list in l is the same, changing one changes them all. This is probably not what you want.
> After all, what should I do if I want to initialize a lot of lists ?
> For example a = [], b = [], c = [],...., z = []
Why do you want to do this? Often using a dict is a good solution to this type of question. For example:
>>> import string
>>> d={}
>>> for c in string.ascii_lowercase:
... d[c] = []
...
>>> d
{'a': [], 'c': [], 'b': [], 'e': [], 'd': [], 'g': [], 'f': [], 'i': [], 'h': [], 'k': [], 'j': [],
'm': [], 'l': [], 'o': [], 'n': [], 'q': [], 'p':
[], 's': [], 'r': [], 'u': [], 't': [], 'w': [], 'v': [], 'y': [], 'x': [], 'z': []}
>>>
Kent
More information about the Tutor
mailing list