0

So, I have two lists:

x =[170 169 168 167 166 165 183 201 219 237 255 274 293 312 331 350]
y =[201,168]

I want to write a conditional if statement that is true only if all the contents of y are in x. How do I do this?

E.g. -- assert(y[0] in x) and assert(y[a] in x) both give True, but assert(y in x) gives False. Similarly, assert( any(y) in x ) raises an error as well.

ap21
  • 2,372
  • 3
  • 16
  • 32
  • Why are you using `assert` like that? `assert` should be used to check the validity of your code's logic, not for validating data. – PM 2Ring Oct 31 '17 at 19:23
  • BTW, is `x` actually a plain Python list? It looks like it could be a Numpy array, in which case you should be using Numpy functions or methods with it. – PM 2Ring Oct 31 '17 at 19:25
  • @PM2Ring Could you please elucidate on your first comment? I agree with the second. – ap21 Oct 31 '17 at 19:28
  • Assertions are used to test for things which should _never_ happen. If the assertion gets raised that means your program logic is wrong and needs to be changed. See [When to use assert](http://archive.is/5GfiG#selection-9.0-9.18) – PM 2Ring Oct 31 '17 at 19:41

3 Answers3

6

Sets are better for this:

set(y) <= set(x)

Note that this relies on your list contents being immutable, as mutable (or, more specifically, unhashable) objects cannot be members of sets. As in this case, lists of integers are fine.

glibdud
  • 7,550
  • 4
  • 27
  • 37
1

all(e in x for e in y)

Similarly, you can use

any(e in x for e in y)

To see if any elements in y are in x.

yinnonsanders
  • 1,831
  • 11
  • 28
1

If you insist on having them be lists, you can use the all() function:

all(item in x for item in y)
kindall
  • 178,883
  • 35
  • 278
  • 309