Create a list of tuples with adjacent list elements if a condition is true
Cleaner Pythonic approach:
>>> [(x,y) for x,y in zip(myList, myList[1:]) if y == 9][(8, 9), (4, 9), (7, 9)]
What is the code above doing:
zip(some_list, some_list[1:])
would generate a list of pairs of adjacent elements.- Now with that tuple, filter on the condition that the second element is equal to
9
. You're done :)
Part of your issue is that myList[i:i]
will always return an empty list. The end of a slice is exclusive, so when you do a_list[0:0]
you're trying to take the elements of a_list
that exist between index 0 and index 0.
You're on the right track, but you want to zip the list with itself.
[(x, y) for x, y in zip(myList, myList[1:]) if y==9]
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.