Python List Comprehensions: Create list b from list a, excluding repeats

2521 views python

I'm trying to solve this problem using list comprehensions. I want to take the list:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

and create a new list b containing all the numbers from a that are below 5, excluding repeats.

I can do this using a for loop:

b = list()
for i in a:
    if i < 5 and i not in b:

which gives me [1, 2, 3], but when I try this using a list comprehension:

b = list()
b = [i for i in a if i not in b and i < 5]

I get a list with repeated values: [1, 1, 2, 3]

Is there a way to exclude repeated values when using list comprehensions?

answered question

Add b = set(b) after your code. set() lets you pick only the unique elements from the given array.

If you really want to do it in a list comprehension without the set trick above, you'll need to test for repetitions in the original list, something like: [n for i, n in enumerate(a) if (n < 5) and (n not in a[:i-1])] (not tested, careful with i == 0).

2 Answers


Using set, you get your list without repeats.

>>> set(a)
{1, 2, 3, 34, 5, 8, 13, 21, 55, 89}

So you can just use (almost) the same list comprehension you were using with set(a) instead of a:

b = [i for i in set(a) if i<5]
#[1, 2, 3]

Note that there is no need to instantiate your list b using b = list() first

posted this

That happens because "b" is still empty while python is creating a temporary list. "b" gets assigned only after list comprehension has created the list.

posted this

Have an answer?


Please login first before posting an answer.