[Tutor] List and comprehension questions
Smith, Jeff
jsmith at medplus.com
Sun Feb 25 16:16:24 CET 2007
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?
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)
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]
Thanks for the input!
Jeff
More information about the Tutor
mailing list