0

If you take the code:

import os
directory = [files for root, dirs, files in os.walk(".")]
imgs = [file[0] for file in [[directory[x][y] for y,file in enumerate(dirs) if file.split('.')[1] == "png"] for x,dirs in enumerate(directory)] if len(file) != 0]

which is four for loops finding all the .png files in a directory and creating a list from the results. My question is: strictly on efficiency of the code, would this be more or less efficient than:

import os
imgs = []
directory = []

for root,dirs,file in os.walk("."):
    directory.append(file)

for x,dirs in enumerate(directory):
    for y,file in enumerate(dirs):
        if file.split('.')[1] == "png":
            imgs.append(file)

Sorry if the answer is obvious, I have never considered efficiency in a program before really. Any explanations would be much appreciated :)

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
BFI01
  • 93
  • 1
  • 2
  • 8
  • possible duplicates -https://stackoverflow.com/questions/22108488/are-list-comprehensions-and-functional-functions-faster-than-for-loops – dsk Mar 12 '19 at 19:15
  • 1
    in cases like this I would say, think about your future self or a future developer who might inherit this, which option would be easier for them to maintain and understand? – gold_cy Mar 12 '19 at 19:20
  • This may help: [](https://stackoverflow.com/questions/16307326/why-this-list-comprehension-is-faster-than-equivalent-generator-expression)https://stackoverflow.com/questions/16307326/why-this-list-comprehension-is-faster-than-equivalent-generator-expression – Jacob Franklin Mar 12 '19 at 19:24

1 Answers1

2

As with any question about efficiency, the only real answer is to profile your code, because it always depends.

That said, there should be no noticeable difference between for loops and list comprehensions (they most likely compile to the same byte code) and you should use what is most readable. In this case, I'd say the nested for loops are far more readable than nested comprehensions.

Soviut
  • 88,194
  • 49
  • 192
  • 260
  • 2
    Unfortunately this answer is not correct. List comprehensions are built up completely, every time they're referenced (unlike generators). For loops obviously have a state, as they contain each nested variable's value. If your comprehension is large and nested, it will very likely be more efficient to use the corresponding for loop. – maccaroo Jun 05 '21 at 06:56