0

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?

  • Could you present what you want to output? Do you want to check if any of the elements in the list "possible" are elements of lst, or elements of any elements of the list lst? To avoid your iterable problem you can check whether "i" is a list and iterate over it only in that case: if isinstance(i, list): for j in i – user1603472 Apr 27 '14 at 20:00
  • The accepted answer to this [related question](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python) might be worth looking at. – Don Roby Apr 27 '14 at 20:00
  • Avoid mixing different types in lists. If your original list was: `[[1,2], [3], [1, 2], [1, 4]]` (note `[3]` instead of `3`) the answer would be really really trivial. With your current `lst` the `for j in i` will raise an exception when the `3` is encountered. Mixing different incompatible types simply increases the number of cases to handle. – Bakuriu Apr 27 '14 at 20:25
  • Thanks for the comments, but I think it would be pretty intensive on equations to change every integer to a list with only the integer, because there are quite alot... – user3579063 Apr 27 '14 at 20:57

2 Answers2

1
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.
Craicerjack
  • 6,203
  • 2
  • 31
  • 39
  • You might want to add a bit more explanation, and maybe a link to the documentation. An answer with just code is looked down upon. – Fred Apr 27 '14 at 20:33
  • 1
    sound - answer updated. Figured though that given his use of loops above he'd under stand the `in` scenario – Craicerjack Apr 27 '14 at 20:41
0

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
Bryan
  • 1,938
  • 13
  • 12