[Tutor] Possible with list comprehension?

Stewart Midwinter midtoad at yahoo.com
Sun Dec 24 21:47:16 CET 2006

List comprehension is a wondering feature, well covered in diveintopython.org. I learned some new tricks there, especially from example 8.15.  Now I'm wondering if I can express the following more succinctly using list comprehension:
for key,val in dataDict.items():
    for i in range(val):

I have a dictionary containing an x,y set of values and occurrences:
{'1':1, '10':2, '100':3, '1000':1, '10000':2} and want to find the mean value, so I need to build a list containing an occurrence weight set of values, and then select the middle value in the list. The list created by the above code snippet will look like this:
[1, 10,10, 100,100,100, 1000, 10000,10000]
and it has 9 elements, so the mean will be the 4.5th (call it 4th) element, so mean = 100. 

My attempt at the list comprehension is complicated by the fact that I'm trying to add elements to the list that's under construction in the list comprehension. How do I refer to the list istself? I tried using 'self' but that didn't work. Would I need to use a lambda function instead?  Here's my attempt:
prods = [eval("for i in range(%i): self.append(%s)" % (val,key)) for key,val in dataDict.items()]
which gives a syntax error.

If I try it with a lambda (below),I get an error message saying self is not defined:
prods = [lambda self=self,val=val,key=key: eval("for i in range(%i): self.append(%s)" % (val,key)) for key,val in dataDict.items()]

Maybe this is beyond the capabilities of list comprehension?  Or perhaps even if it's possible it's too obtuse and not pythonic idiom?  Certainly my original version at the top of this message is clear and readable. It's just on three lines instead of one. Perhaps that isn't so bad. 


Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 

More information about the Tutor mailing list