Python | Preceding element tuples in list

Sometimes, while working with Python list, we can have a problem in which we need to construct tuples, with the preceding element, whenever that element matches a particular condition. This can have potential application in day-day programming. Let’s discuss a way in which this task can be performed.

Method : Using zip() + list comprehension
This task can be performed using the combination of above functionalities. In this, the zip() performs the task of construction of tuples and the catering of condition matching and iteration is handled by list comprehension.

Code :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Preceding Tuple elements in list
# using zip() + list comprehension
  
# initialize list
test_list = [1, 4, 'gfg', 7, 8, 'gfg', 9, 'gfg']
  
# printing original list
print("The original list is : " + str(test_list))
  
# initialize ele 
ele = 'gfg'
  
# Preceding Tuple elements in list
# using zip() + list comprehension
res = [(x, y) for x, y in zip(test_list, test_list[1 : ]) if y == ele]
  
# printing result
print("Tuple list with desired Preceding elements " + str(res))

chevron_right


Output :

The original list is : [1, 4, 'gfg', 7, 8, 'gfg', 9, 'gfg']
Tuple list with desired Preceding elements [(4, 'gfg'), (8, 'gfg'), (9, 'gfg')]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.