Joakim Nyholm Joakim Nyholm - 1 year ago 82
Python Question

Python: Checking if X number of lists contain a certain element

So I'm very new to python and trying to figure out a good way to check several sublists for a certain statement. I thought that

if A in list:
#Do this

Would do what I wanted but it doesn't seem to be working. This does however work and achieve what I want.

if A in list[1] or A in list[2] or A in list[3] on:
#Do this `

The problem is that the number of lists depend on a chosen input variable, so I want something in the style of

if A in list[range(0,B)]
#Do this

Is there a way to achieve something like this?

Answer Source

Try this:

if any(A in lst for lst in lists):

Note that I renamed your variable to lists, it's a bad idea to name it list as it clashes with a built-in function of the same name.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download