Compare the values of two lists

Asked

Viewed 47 times

0

So, I just started learning Python and I’d like to know how to compare the values of two lists, more specifically, know the values that match them, example

a = [30, 35, 40, 50]
b = [25, 35, 40, 55]

result = [35, 40]

2 answers

0

You can use the class set() which provides some functions such as union, intersection, difference and among others, in your case you that intersection, then just do result = set(a) & set(b) that will return {35, 40} which is an object of type 'set', which to transform into list is only to do the conversion result = list(result), or convert during operation result = list(set(a) & set(b))

You can see more about set in: https://www.programiz.com/python-programming/set.

-1

Well, it depends on how you want to compare. If you want to know if the values are equal, do this:

a = [30, 35, 40, 50]
b = [25, 35, 40, 55]

for listA in a:
  for listB in b:
    if listA == listB:
      print("O valor %s e igual ao valor %s"%(listA, listB))
    else:
      print("O valor %s nao e igual ao valor %s"%(listA, listB))

If you want to compare to see if the values are higher or lower, change "==" to ">"(higher), "<"(lower). " >="(greater or equal), "<="(less or equal).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.