Reputation: 39
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
Reputation: 4867
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]
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.
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
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
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
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
Upvotes: 3