Skip to content Skip to sidebar Skip to footer

List Comprehension Not Working

I want to put the unique items from one list to another list, i.e eliminating duplicate items. When I do it by the longer method I am able to do it see for example. >>>new

Solution 1:

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

Maybe you can try this:

>>> new_list = []
>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> unused=[new_list.append(word) for word in a if word notin new_list]
>>> new_list
['It', 'is', 'the', 'east', 'and', 'Juliet', 'sun']
>>> unused
[None, None, None, None, None, None, None]

Notice:

append() returns None if the inserted operation is successful.

Another way, you can try to use set to remove duplicate item:

>>> a = ['It', 'is', 'the', 'east', 'and', 'Juliet', 'is', 'the', 'sun']
>>> list(set(a))
['and', 'sun', 'is', 'It', 'the', 'east', 'Juliet']

Solution 2:

If you want a unique list of words, you can use set().

list(set(a))
# returns:
# ['It', 'is', 'east', 'and', 'the', 'sun', 'Juliet']

If the order is important, try:

new_list= []
for word in a:if not a in new_list:new_list.append(word)

Post a Comment for "List Comprehension Not Working"