-12

I want to check if for example the int 2 comes after or before another 2:

list = [2, 2, 3]
if 2 and 2 in list:
    print "True"

And if the list is this:

list = [2, 3, 2]
print "False"

thx

Telep0rter
  • 47
  • 11

2 Answers2

1

Try this:

def check(list_):
    last = None
        for element in list_:
            if element == last:
                return True
            else:
                last = element
    return False
Batman
  • 8,571
  • 7
  • 41
  • 80
0
a = [0, 2, 15, 13, 13, 5, 12, 3, 1, 3, 14, 14, 17, 20, 0, 14, 2, 0,
     1, 10, 5, 13, 15, 13, 19, 11, 20, 5, 4, 17, 20, 7, 4, 20, 20,
     19, 3, 20, 20, 0, 14, 8, 18, 0, 18, 2, 5, 15, 12, 20, 5, 7, 12,
     6, 17, 18, 15, 12, 2, 16, 6, 11, 14, 20, 8, 4, 11, 10, 15, 6,
     10, 19, 1, 20, 6, 19, 2, 5, 13, 7, 5, 18, 11, 11, 3, 0, 11, 3,
     14, 18, 15, 11, 2, 9, 12, 0, 18, 1, 4, 2]

Run through the list once to find all the pairs and put them in a set

z = {x for x, y in zip(a, a[1:]) if x == y}

>>> z
{11, 20, 13, 14}

Then use it like this:

>>> n = 2
>>> n in z
False
>>> n = 13
>>> n in z
True
>>> 

zip(a, a[1:])

will produce tuples of (a[0], a[1]), (a[1], a[2]), (a[2], a[3]), ...

The pairwise Itertools Recipe will do the same thing.

wwii
  • 23,232
  • 7
  • 37
  • 77