How to check if one list is inside the other?

Asked

Viewed 2,225 times

1

My code:

n = [int(input()) for c in range(0, 5)]
lista = list(range(0, 10))
if n not in lista:
    print('1')
else:
    print('2')

Digit 1, 2, 3, 4, 5 and the answer is "1", and the numbers from 1 to 5 are within the "list" that includes the numbers from 0 to 10, so I don’t think I’m correctly relating one list to the other. I would like to know how to check if the values of the first list are within the second, if the input is the example I used.

  • I don’t understand. You want to know if the variable is a list or if a certain value is inside the list?

  • I edited the question, now the doubt became clearer?

  • 1

    Change your if n not in lista: for if set(n).intersection(lista):, see if this helps you.

  • It worked, you can explain to me how this structure works and give other examples of the type to use for if "n" is not in "list"?

  • I already publish the answer and explain.

1 answer

3


You use the method intersection and check if there are common values in your set or list. Basically, it checks whether the elements of n belongs to lista.

Behold:

n = [int(input()) for c in range(0, 5)]

lista = list(range(0, 10))

if set(n).intersection(lista):
  print('1')
else:
  print('2')

You can consult other methods that can help you with list operations.

See more about the Intersection.

  • If I go in with 1, 11, 12, what will the output be? Will it be the right outcome? Why? And if I enter with 1, 1, 1? The output will be 1 even if the input is not contained in lista, since it has 2 more?

  • @Andersoncarloswoss any element in the range of 0..9 will be compatible with the elements of the lista, unless you enter with values above 9 that in this case will not be on this track.

  • But list 1, 11, 12 will not give an intersection equal to 1 and enter if, even if 11 and 12 do not belong?

  • @Andersoncarloswoss do not know if I understand very well sorry. If you enter with the values 1, 11, 12 will give error because you need to enter with 5 elements, however, if you enter with 1, 11, 12, 13, 14 will satisfy the condition of if because 1 intersects with values in lista.

Browser other questions tagged

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