Phillip Phillip - 1 year ago 65
Python Question

Create list of tuples with adjacent list elements if a condition is true

I'm trying to create a list of sets where the set is the number 9 and the number before it in the list.

Input List

myList = [1,8,9,2,4,9,6,7,9,8]

Desired Output

sets = [(8,9),(4,9),(7,9)]


sets = [list(zip(myList[i:i],myList[-1:])) for i in myList if i==9]

Current Result


Answer Source

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 :)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download