[Tutor] assigning list to keys

wesley chun wescpy at gmail.com
Tue Jul 14 09:09:51 CEST 2009


> The other day I needed to pack a dictionary, the value of each key was a list. In the code I was packing the list and the dictionary at the same time. First I tried something like this:
>
> list = []
> dict = {}
> x = 1
>
> dict['int'] = list.append(x)
>
> The result was {'int': None}. Why is the value None?


the reason why the value is None is because the output of the list
append() method is None (and will always be None unless they change
it).

the sole purpose of the append() method is to add an element to the
end of a list. in your case, you added the integer 1 to your list
named 'list'. that's all it does... 'list' is changed, and no value to
return is necessary, hence the reason why Python returns None. if you
want the last value you appended in your code, you need to access
list[-1].

on another note: you should avoid naming your variables with the same
names as data types, i.e., list, str, dict, tuple, int, etc., because
you shadow/hide the factory function of the same name. in other words,
in your code above, you can no longer access list() nor dict().

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Python Web Development with Django", Addison Wesley, (c) 2009
http://withdjango.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list