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 🙂

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)