0

I'm sure that this has been asked before, but I've tried about a half a dozen keywords and I couldn't find it.

I have this for loop that appends a letter to a list if it doesn't exist:

word_list = ['cat', 'dog', 'rabbit']
letter_list = []

for word in word_list:
    for letter in word:
        if letter not in letter_list:
            letter_list.append(letter)

print(letter_list)
# ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

I'm trying to do the same thing using list comprehension, but I don't know how to have my if statement test the letter_list_comp before it is defined. This is what I want to do:

letter_list_comp = [letter for word in word_list for letter in word if letter not in letter_list_comp]
Al-Baraa El-Hag
  • 770
  • 6
  • 15

1 Answers1

0

I don't think it's possible. On the side note set is designed to keep unique elements and in operation on set is much more performant then on list - O(1) vs O(n) in CPython.

So you could either:

for word in word_list:
    for letter in word:
        my_set.add(letter)

or

my_set = set("".join(word_list))
yjay
  • 942
  • 4
  • 11