I am newbie who can explain this code to me?

Peter Otten __peter__ at web.de
Tue Sep 20 09:12:39 EDT 2016


380162267qq at gmail.com wrote:

> 在 2016年9月20日星期二 UTC-4上午8:17:13,BartC写道:
>> On 20/09/2016 13:12, 380162267qq at gmail.com wrote:
>> >>>> d = {}
>> >>>> keys = range(256)
>> >>>> vals = map(chr, keys)
>> >>>> map(operator.setitem, [d]*len(keys), keys, vals)
>> >
>> > It is from python library. What does [d]*len(keys) mean?
>> > d is the name of dict but put d in [] really confused me.
>> >
>> 
>> if len(keys) is 5 then [d]*5 is:
>> 
>>     [d,d,d,d,d]
>> 
>> [d] is a list, containing one item, a dict if that is what it is.
>> 
>> --
>> Bartc
> 
> Thank you. I understand now

It should be noted that the code above is really bad Python.
Better alternatives are the simple loop

d = {}
for i in range(256):
     d[i] = chr(i)

or the dict comprehension

d = {i: chr(i) for i in range(256)}

and even

keys = range(256)
d = dict(zip(keys, map(chr, keys)))

because they don't build lists only to throw them away. 


Also, creating a list of dicts or lists is a common gotcha because after

outer = [[]] * 3

the outer list contains *the* *same* list three times, not three empty 
lists. Try

outer[0].append("surprise")
print(outer)

in the interactive interpreter to see why the difference matters.


Finally, if you are just starting you might consider picking Python 3 
instead of Python 2.




More information about the Python-list mailing list