0

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:
        b.append(i)

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?

  • Add b = set(b) after your code. set() lets you pick only the unique elements from the given array. – Rashid Sep 16 '18 at 21:44
  • 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`). – Francis Colas Sep 16 '18 at 21:48

2 Answers2

2

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

sacuL
  • 49,704
  • 8
  • 81
  • 106
  • 1
    Note that sets destroy the order of the list. – Kevin Sep 16 '18 at 21:41
  • True, depends on what OP wants to do, but if order matters, another strategy needs to be taken – sacuL Sep 16 '18 at 21:42
  • @sacul I hadn't learned about `set()` yet, thanks for that! Also, the only reason I used `b = list()` in my code was because without it my list comprehension attempt gave me a `NameError` about `b` not being defined. Thanks again! – Danny McVey Sep 16 '18 at 21:50
0

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.

Peanut
  • 175
  • 11