[Tutor] iterating

Kent Johnson kent37 at tds.net
Mon Apr 30 17:17:42 CEST 2007


Cecilia Alm wrote:
> 1) Unordered maps/collections like sets and dictionaries also seem to
> support iterating over set members or dictionary keys with "for x in
> y" syntax. As far as I can tell, the following three ways generally
> behave the same way, or is there a difference in behavior between:
> 
> a) for key in dictionary:
> b) for key in dictionary.keys():
> c)  mykeys = dictionary.keys()
>      for k in mykeys:

These are equivalent in most common usage but there is a difference 
which can be significant. Calling dict.keys() creates an actual list 
with all the keys in it which is not created when you iterate the 
dictionary directly. In most cases this doesn't matter but for a huge 
dictionary it might. Also if you are adding or deleting from the dict 
during the iteration then dict.keys() is safer because the list of keys 
is created before the add and delete. Using dict.iterkeys() is more 
equivalent to 'for key in dictionary' because it doesn't create the 
intermediate list.

Of course using c) you will also have the variable mykeys available 
which is not the case in a) and b)
> 
> 2) The following three ways for manipulating objects in a list with a
> function will generally do the same thing, right? (but the last two
> have a shorter syntax).
> 
> a)  newls = []
>      for entry in mylist:
>         newls.append(function(entry))
> 
> b)  newlist = map(function, mylist)
> 
> c)  newlist = [function(entry) for entry in mylist]

Yes, pretty much. After a) and c) the entry variable will still be 
defined. For c) this is considered a bug and IIRC will change with 
Python 3. IMO modern usage tends toward c).

Kent


More information about the Tutor mailing list