Dictionary and List

Hrvoje Niksic hniksic at srce.hr
Fri Oct 22 19:52:21 EDT 1999


sorot at my-deja.com writes:

> for i in range(0,len(x)):
>    my_dict['a'] = x[i]
>    my_list.append(my_dict)

A side note: the above `for' loop shows a construct I frequently see
in Python sources that seems borrowed from C.  I don't think there is
any need to create a [0, len(x)) range, and then iterate over it; the
Pythonish way of writing it would be:

for item in x:
  my_dict['a'] = item
  ...

Not only does it make it clearer what is going on (item iterates over
sequence x), but it's also more efficient because the consing of
range() is avoided.




More information about the Python-list mailing list