0

How can I form an array (c) composed of elements of b which are not in a?

a=[1,2,"ID123","ID126","ID124","ID125"]
b=[1,"ID123","ID124","ID125","343434","fffgfgf"]
c= []

Can this be done without using a list comprehension?

dckrooney
  • 2,943
  • 1
  • 21
  • 28
Rajeev
  • 42,191
  • 76
  • 179
  • 280

3 Answers3

6

If the lists are long, you want to make a set of a first:

a_set = set(a)
c = [x for x in b if x not in a_set]

If the order of the elements don't matter, then just use sets:

c = list(set(b) - set(a))

Python lists don't offer a direct - operator, as Ruby arrays do.

Ned Batchelder
  • 345,440
  • 70
  • 544
  • 649
1

Using list comprehension is most straight forward:

[i for i in b if i not in a]
c
['343434', 'fffgfgf']

However, if you really did not want to use list comprehension you could use a generator expression:

c = (i for i in b if i not in a)

This will also not generate the result list all at once in memory (in case that would be a concern).

Levon
  • 129,246
  • 33
  • 194
  • 186
0

The following will do it:

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

If a is long, it might improve performance to turn it into a set:

a_set = set(a)
c = [v for v in b if v not in a_set]
NPE
  • 464,258
  • 100
  • 912
  • 987