0

I have two list a and b I have to get result of two list one with elements which are in both and one in which elements of b which aren't present in a.I have to write the code in python.output and should look like this.

    a = ['product','shampoo','vivel','spark']
    b = ['random','product','shampoo','nothing']
    c = ['product','shampoo']
    d = ['random','nothing']

I need an efficient one as I have to do this some process many times Thank you, please let me know if there is any unclarity.

A-dude
  • 161
  • 1
  • 10

2 Answers2

4

You can use set operations, since that is essentially what you're after.

>>> a = ['product','shampoo','vivel','spark']
>>> b = ['random','product','shampoo','nothing']

The list c would be the result of a set intersection

>>> c = set(a).intersection(b)
>>> c
{'shampoo', 'product'}

The list d would be the result of a set difference of a from b.

>>> d = set(b).difference(a)
>>> d
{'random', 'nothing'}

There are operators for sets that perform these operations as well

>>> set(a) & set(b)
{'shampoo', 'product'}
>>> set(b) - set(a)
{'random', 'nothing'}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

An efficient way to perform this task consists of using set -

a = ['product','shampoo','vivel','spark']
b = ['random','product','shampoo','nothing']

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

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

print(c)

print(d)

Output -

['product', 'shampoo']
['nothing', 'random']
Vedang Mehta
  • 2,214
  • 9
  • 22