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
  • 3,041
  • 3
  • 22
  • 28
Rajeev
  • 44,985
  • 76
  • 186
  • 285

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
  • 364,293
  • 75
  • 561
  • 662
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
  • 138,105
  • 33
  • 200
  • 191
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
  • 486,780
  • 108
  • 951
  • 1,012