Search code examples
pythonlistlist-comprehension

Transform nested for-loops to list comprehension


I have the following code:

  files_to_upload = []
  for file_name in ignore_list:
      for file_path in files_not_in_Azure:
          if file_name in file_path:
              files_to_upload.append(file_path)

How can this be written in one line using a list comprehension?


Solution

  • You can do the following, using itertools.product:

    from itertools import product
    files_to_upload = [file_path for file_path, file_name in product(ignore_list, files_not_in_Azure) if file_name in file_path]
    

    Note that using multiple for clauses is more verbose here. (Some also consider it to be poor style.)