How to convert this for a loop to a list comprehension?

I have a for loop as follows:

for i in conversion: for f in glob.glob(i): print(os.path.getsize(f)) 

I want to convert this to a list comprehension:

Tried this:

 [os.path.getsize(f) for f in glob.glob(i) for i in conversion] 

but does not work.

+4
source share
1 answer

The order of for loops in the understanding of a double list is the same order you would use with nested loops:

 [os.path.getsize(f) for i in conversion for f in glob.glob(i)] 

This is a bit confusing because you expect the inner loop to be more β€œinner”, but as soon as you realize that this is the same order as the nested loop, everything is simple :)

+9
source

All Articles