Skip to content Skip to sidebar Skip to footer

List Comprehension Output Is None

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

Solution 1:

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

Solution 2:

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

Solution 3:

If order doesn't matter, do this:

resultlist = list({i for word in wordlist for i in word})

Post a Comment for "List Comprehension Output Is None"