Roberto Demicheli
Roberto Demicheli

Reputation: 39

Python: List comprehension, combining 2 lists into 1 with unique values

I want to create a list that contains only elements from the original list a that are not in list b.

I have tried using list comprehension, but don’t understand why the numbers in the new list are repeated three times.

a = [3, 6, 7, 9, 11, 14, 15]

b = [2, 6, 7, 10, 12, 15]

c = [x for x in a if x not in b 
       for y in b if y not in a]

I expected this result:

[3, 9, 11, 14]

Upvotes: 2

Views: 370

Answers (5)

Christopher Rucinski
Christopher Rucinski

Reputation: 4867

Solution

You added too much code

a = [3, 6, 7, 9, 11, 14, 15]
b = [2, 6, 7, 10, 12, 15]

c = [x for x in a if x not in b]

This gives the following result just as you wanted!!

print(c)

# [3, 9, 11, 14]

Why Repeated 3 times?

Well look at the orginal data again

original = [3, 6, 7, 9, 11, 14, 15]
# Index     0  1  2  3   4   5   6
#           ✓  x  x  ✓   ✓   ✓   x  

second = [2, 6, 7, 10, 12, 15]
#         0  1  2   3   4   5
#         ✓  x  x   ✓   ✓   x

You get 4 unique numbers [3, 9, 11, 14] because there are 4 numbers in original that are not in the second list.

You get 3 repeated numbers because there are 3 numbers in second that are not in the orginal list.

Testing

You can test this idea by expanding the lists

original = [3, 6, 7, 9, 11, 14, 15]
second = [2, 6, 7, 10, 12, 15, 100, 200]

# print(c)
# [3, 3, 3, 3, 3, 9, 9, 9, 9, 9, 11, 11, 11, 11, 11, 14, 14, 14, 14, 14]

Now we have 5 unique values in the second list, so it's repeated 5 times now!

Upvotes: 2

Jab
Jab

Reputation: 27495

If you don't need to preserve order then you can use set.difference

a = [3, 6, 7, 9, 11, 14, 15]
b = [2, 6, 7, 10, 12, 15]
c = set(a) - set(b)

Or if you want to use a comprehension:

c = [n for n in a if n not in b]

Upvotes: 0

Sadrach Pierre
Sadrach Pierre

Reputation: 121

a = [3, 6, 7, 9, 11, 14, 15]
b = [2, 6, 7, 10, 12, 15]
c = []

for i in a:
    if i not in b:
        c.append(i)

Upvotes: 0

Dumb chimp
Dumb chimp

Reputation: 454

An easier way would be to use sets.

set_a = set(a)
set_b = set(b)

c = list(set_a - set_b) #Using set operator difference
c.sort() #If you need to have it in order

Set Operator Difference

Upvotes: 3

snowneji
snowneji

Reputation: 1136

This works:

[*filter(lambda x: x not in b, a)]

Upvotes: 0

Related Questions