fizis fizis - 2 months ago 10
Python Question

Why doesn't this list comprehension work?

The purpose of the code is to collect all the chars in wordlist, I did the following:

wordlist = ['cat','dog','rabbit']
[c for c in word for word in wordlist]


The output is strange:

['r',
'r',
'r',
'a',
'a',
'a',
'b',
'b',
'b',
'b',
'b',
'b',
'i',
'i',
'i',
't',
't',
't']


I know that I can do it using:

[ch for ch in "".join(wordlist)]


or

[word[i] for word in wordlist for i in range(len(word))]


However my first proposal seems also right, can anyone tell me why the first doesn't work?

Answer

You have the for statements in the wrong order:

[c for c in word for word in wordlist]

Should be

[c for word in wordlist for c in word]

The way to remember the order of the for statements in a list comprehension is to imagine how you would write it as a loop. The order follows the indentation:

result = []
for word in wordlist:
    for c in word:
        result.append(c)