0

I'm wondering if this is a good idea to avoid nested loops using List Comprehension in the case bellow

Imagine the following list of names in a config.py file

# config.py
NAME_LIST = [
    'name1',
    'name2',
    (...)
]

I'm using this list of names to go though multiple different directories, and for each of the files I find, I read the content of the files and process data.

This is my actual code:

import config

def foo():

    for w in config.NAME_LIST:
        folder = "/data/test/{name}/in".format(name=w)
        files = list_files(folder) # return a list of files found in folder

        for f in files:
            content = read_file(folder, f) # read files content
            # (... do some stuff to process data)

I really want to avoid a nested loop to keep the code as flat as possible.

I tried to approach this using List Comprehension but not sure this is the best solution as I don't want it to return anything.

Here is what I've done:

import config

def foo():

    def _process(f):
        """function called from list comprehension to avoid doing nested loops"""
        content = read_file(folder, f)  # read files content
        # (... do some stuff to process data)

    for w in config.NAME_LIST:
        folder = "/data/test/{name}/in".format(name=w)
        files = list_files(folder) # return a list of files found in folder
        [_process(f) for f in files] # using list comprehension 

Are List Comprehension a good solution in this case? Any better way to achieve this?

smallwat3r
  • 1,037
  • 1
  • 8
  • 28
  • 2
    No, this is absolutely **not** a use-case for a list-comprehension. A list comprehension is for *creating lists*, not as a "one-liner" substitute for for-loops. You create a list and immediately discard it. Just stick to your loop. – juanpa.arrivillaga Jun 20 '18 at 19:41

1 Answers1

1

There are some hacks with filter or any to avoid the unnecessary output (Is there a map without result in python?) but the for loop is probably the most idiomatic approach? Is there a reason you want it flat?

JoshuaF
  • 1,124
  • 2
  • 9
  • 23