[Tutor] List and comprehension questions

Kent Johnson kent37 at tds.net
Sun Feb 25 17:17:22 CET 2007

Smith, Jeff wrote:
> I'm getting use to using list iteration and comprehension but still have
> some questions.
> 1. I know to replace
>     for i in range(len(list1)):
>         do things with list1[i]
> with
>     for li in list1:
>         do things with li
> but what if there are two lists that you need to access in sync.  Is
> there a simple way to replace
>     for i in range(len(list1)):
>         do things with list1[i] and list2[i]
> with a simple list iteration?

Use zip() to generate pairs from both (or multiple) lists:
for i1, i2 in zip(list1, list2):
   do things with i1 and i2

> 2. I frequently replace list iterations with comprehensions
>     list2 = list()
>     for li in list1:
>         list2.append(somefun(li))
> becomes
>     list2 = [somefun(li) for li in list1]
> but is there a similar way to do this with dictionaries?
>     dict2 = dict()
>     for (di, dv) in dict1.iteritems():
>         dict2[di] = somefun(dv)

You can construct a dictionary from a sequence of (key, value) pairs so 
this will work (using a generator expression here, add [] for Python < 2.4):
dict2 = dict( (di, somefun(dv) for di, dv in dict1.iteritems() )

> 3. Last but not least.  I understand the replacement in #2 above is the
> proper Pythonic idiom, but what if a list isn't being created.  Is it
> considered properly idiomatic to replace
>     for li in list1:
>         somefun(li)
> with
>     [somefun(li) for li in list1]

I think this is somewhat a matter of personal preference; IMO it is 
ugly, I reserve list comps for when I actually want a list.


More information about the Tutor mailing list