You were pretty close, I'll show you an alternative way that might be more intuitive if you're just starting out:
sets = [(myList[i-1], myList[i]) for i in range(len(myList)) if myList[i] == 9]
Get the index in the range of the list lenght, and if the value at the position i
is equal to 9
, grab the adjacent elements.
The result is:
sets
[(8, 9), (4, 9), (7, 9)]
This is less efficient than the other approaches but I decided to un-delete it to show you a different way of doing it. You can make it go a bit faster by using enumerate()
instead:
sets = [(myList[i-1], j) for i, j in enumerate(myList) if j == 9]
Take note that in the edge case where myList[0] = 9
the behavior of the comprehension without zip
and the behavior of the comprehension with zip
is different.
Specifically, if myList = [9, 1, 8, 9, 2, 4, 9, 6, 7, 9, 8]
then:
[(myList[i-1], myList[i]) for i in range(len(myList)) if myList[i] == 9]
# results in: [(8, 9), (8, 9), (4, 9), (7, 9)]
while:
[(x, y) for x, y in zip(myList, myList[1:]) if y==9]
# results in: [(8, 9), (4, 9), (7, 9)]
It is up to you to decide which of these fits your criteria, I'm just pointing out that they don't behave the same in all cases.