-1

I have a list of glob patterns. For each glob pattern, I get the matching file list, and I want to combine all the file lists with list comprehension to be one flattened list:

patterns = [
    "some_pattern1",
    "some_pattern2"
]
all_files = []
all_files.extend(glob.glob(pattern)) for pattern in patterns

However this gives me a syntax error, I can do the list merge with:

for pattern in patterns:
    all_files.extend(glob.glob(pattern))

I think those two syntax are equivalent. Why the list comprehension doesn't work with extend?

For exmaple, consider some_pattern1 matches two files [1.txt, 2.txt]; some_patter2 matches [3.txt, 4.txt], I'm looking for a way to combine the two lists to be: [1.txt, 2.txt, 3.txt, 4.txt]

Chen Xie
  • 3,849
  • 8
  • 27
  • 46

2 Answers2

1

There is no problem with the extend method.

Your syntax is wrong. You should write it this way:-

patterns = [
    "some_pattern1",
    "some_pattern2"
]
all_files = []
all_files.extend([glob.glob(pattern) for pattern in patterns])

It will return output like this:-

[['1.txt', '2.txt'], ['3.txt', '4.txt']]

Add this to the code:

sum(all_files, [])

Now the output will be like this:-

['1.txt', '2.txt', '3.txt', '4.txt']
Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17
0

This is simply invalid syntax, all_files.extend(glob.glob(pattern)) for pattern in patterns looks like the syntax for list comprehension, which you're not trying to perform here.

Sush
  • 1,169
  • 1
  • 10
  • 26