Reputation: 1
I need to check if an element is part of a list, but the list looks like:
>>> lst = [[1,2], 3, [1,2], [1,4]]
>>> possible = [1,4]
I tried to check it with multiple for-loops, but the problem is the integer, it isn't iterable.
>>> for pos_elem in range(len(possible)):
for i in lst:
for j in i:
if possible[pos_elem] == j:
print j
Is there a code that will check every element of lst without error?
Upvotes: 0
Views: 339
Reputation: 6332
if possible in lst:
#do something
Python has membership operators, which test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators. in
and not in
in
Evaluates to true if it finds a variable in the specified sequence
and false otherwise. not in
Evaluates to true if it does not finds a variable in the
specified sequence and false otherwise.Upvotes: 1
Reputation: 2078
You could use python's built in type
to check if the element in the list is a list or not like so:
lst = [[1, 2], 3, [1, 2], [1, 4]]
possible = [1, 4]
for element in lst:
#checks if the type of element is list
if type(element) == list:
for x in element:
if x in possible:
print x
else:
if element in possible:
print element
Prints:
1
1
1
4
Upvotes: 0