-1

I'm new to python and I wanted to try to use list comprehension but outcome I get is None.

print
wordlist = ['cat', 'dog', 'rabbit']
letterlist = []
letterlist = [letterlist.append(letter) for word in wordlist for letter in word if letter not in letterlist]
print letterlist

# output i get: [None, None, None, None, None, None, None, None, None]
# expected output: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']

Why is that? It seems that it works somehow because I get expected number of outcomes (9) but all of them are None.

falsetru
  • 357,413
  • 63
  • 732
  • 636
JeremyK
  • 147
  • 1
  • 1
  • 10

3 Answers3

2

list.append(element) doesn’t return anything – it appends an element to the list in-place.

Your code could be rewritten as:

wordlist = ['cat', 'dog', 'rabbit']
letterlist = [letter for word in wordlist for letter in word]
letterlist = list(set(letterlist))
print letterlist

… if you really want to use a list comprehension, or:

wordlist = ['cat', 'dog', 'rabbit']
letterset = set()
for word in wordlist:
    letterset.update(word)
print letterset

… which is arguably clearer. Both of these assume order doesn’t matter. If it does, you could use OrderedDict:

from collections import OrderedDict
letterlist = list(OrderedDict.fromkeys("".join(wordlist)).keys())
print letterlist
jbg
  • 4,903
  • 1
  • 27
  • 30
1

list.append returns None. You need to adjust the expression in the list comprehension to return letters.

wordlist = ['cat', 'dog', 'rabbit']
letterset = set()
letterlist = [(letterset.add(letter), letter)[1]
              for word in wordlist
              for letter in word
              if letter not in letterset]
print letterlist
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Cute, but I _hatess_ list comps with side effects. Still, I guess it's better than filling a list comp with a bunch of `None`s... – PM 2Ring Jan 02 '16 at 12:20
0

If order doesn't matter, do this:

 resultlist = list({i for word in wordlist for i in word})
Paweł Kordowski
  • 2,688
  • 1
  • 14
  • 21
Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57