Python list comprehension evaluation

I have a list comprehension that I hope is more revealing than the loop equivalent. However, I'm not sure how python values โ€‹โ€‹comprehension. If he estimates the width first, then the operation is expensive, however it seems prudent to estimate them all at each step, requiring the data to be evaluated once and passed through the loops. The understanding of the list I'm interested in is below.

[(Counter(x.keys()), x) for x in [Counter([hashxx(w)%100000 for w in n.split()]) for n in x]]

      

How will this be assessed? will the hash be computed and then bubble up to the outer contour or will all the hashes be computed first?

+3


source to share


1 answer


List comprehension is always fully evaluated where it occurs, just like any other type expression a+b

. List comprehension does not "know" that it is within another list comprehension, so it cannot behave differently on that basis.

If you want to iterate "bit by bit", generating only one element from the list comprehension at a time, then use the expression >.



Here's a simple comparison:

def inner(x):
    print("inner")
    return x.upper()

def outer(x):
    print("outer")
    return x+"!"

# inner comprehension is a list comprehension
>>> [outer(x) for x in [inner(x) for x in ('a', 'b', 'c')]]
inner
inner
inner
outer
outer
outer
['A!', 'B!', 'C!']

# inner comprehension is a generator comprehension
>>> [outer(x) for x in (inner(x) for x in ('a', 'b', 'c'))]
inner
outer
inner
outer
inner
outer
['A!', 'B!', 'C!']

      

+4


source







All Articles