Nawendu Singh
Nawendu Singh

Reputation: 51

How does nested list comprehension work in Python?

I have to write a list comprehension for making a list with alphabets from a list of strings without repeating the alphabets. for example:

words = ['cat', 'dog', 'rabbit']

should return

['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

I first used nested for loops with if like this:

words = ['cat', 'dog', 'rabbit']
alphabets = []
for each_word in words:
    for x in each_word:
        if x not in alphabets:
            alphabets.append(x)
print(alphabets)

Now how should i convert this to list comprehension with the if statement? Right now i can accomplish this :

alphabets= [x for x in each_word for each_word in words]

which returns

['c', 'a', 't', 'd', 'o', 'g', 'r', 'a', 'b', 'b', 'i', 't']

I need this as:

 ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

Upvotes: 1

Views: 206

Answers (1)

Reut Sharabani
Reut Sharabani

Reputation: 31339

list comprehensions are to be used carefully. They quickly get out of hand. They also aren't built to mutate state (in this case alphabets).

To answer your question:

[alphabets.append(letter) or letter for word in words for letter in word if letter not in alphabets]

But this is very hacky and bad. Don't do it.

It works because append returns None, which makes or return the next (or last) value. Don't even bother with it. It's bad code.


You could do:

from itertools import chain

alphabets = set(chain.from_iterable(words))

Instead.

Upvotes: 5

Related Questions