Check List elements within other Python lists

Asked

Viewed 145 times

0

Good,

I have two lists

lista1 = [0,1,2,3]
lista2 = [0,1,2,3,4,5]

How do I confirm that all elements of list 1 are within Lista2 ?

For example :

lista1 = [0,1,2]
lista2 = [1,2,3,4]

lista3 = [0,1,2,3]
lista4 = [0,1,2,3,4]

All elements of list1 are not within Lista2 but all elements of list3 are within list4!

I’ve tried to do it simply by doing :

if lista1 in lista2 :
    print('todos dentro')

But it doesn’t work! Somebody help me?

  • maybe this material can give you a hand

  • You want to apply set theory to lists, have you thought about using ensembles? So I could do {0, 1, 2, 3} <= {0, 1, 2, 3, 4, 5} == True

  • First, we need to define a detail. The list [1, 1] is on the list [1, 2]? That is, when there are repeated elements, they should be considered the same or distinct element?

  • @Andersoncarloswoss Yes, we consider the same element

1 answer

0


if lista1 in lista2 :
    print('todos dentro')

What you compared here is not whether one list contains all the elements of the other, but whether one list contains the other. These are separate things.

  1. a = [1, 2], b = [1, 2, 3] (a in b => False)
  2. a = [1, 2], b = [[1, 2], 3] (a in b => True)

In the situation (1) the list b contains all elements of a; in the situation (2) the list b contains the list a. You need to check the situation (1), but checked the situation (2).

What you can do to check is make a loop through the elements of the first list and check one by one if they are also in the second list. In Python, the simplest way to do this would be:

if all(i in b for i in a):
    print('Todos dentro')

I mean, check whether i is in b for all i that belongs to a.

Or, as commented, you can use set theories. In Python, you can create a set from a list from the structure set:

a = set([1, 2])
b = set([1, 2, 3])

And so use the method set.issubset to check if one set is sub-set of another:

if a.issubset(b):
    print('Todos dentro')

Or by the operator <=, who does the same thing:

if a <= b:
    print('Todos dentro')

Browser other questions tagged

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