Home > Blockchain >  Compare the values of one list with the values of another list
Compare the values of one list with the values of another list

Time:12-02

I have the list a:

a = ['wood', 'stone', 'bricks', 'diamond']

And the list b:

b = ['iron', 'gold', 'stone', 'diamond', 'wood']

I need to compare lists and if value of list a equals with value from list b, it will be added to a list c:

c = ['wood', 'stone', 'diamond']

How can I compare these lists?

CodePudding user response:

You could convert them to sets and get the intersection.

list(set(a) & set(b))

CodePudding user response:

When comparing values of one list to another you can use one of two options:

First you could use a for loop like so:

c = []

for element in a:
    if element in b:
        c.append(element)
print(c)

This is a rather chunky way of doing it, rather you could just use a comprehension like so:

c = [element for element in a if element in b]
print(c)

Both of these answers give the output of:

['wood', 'stone', 'diamond']

Hope this helps.

  • Related