Python | Previous tuples of items in the list

Python Methods and Functions

Method: Using zip () + List Comprehension
This task can be accomplished using a combination of the above functions. In this, zip () performs the task of building tuples, and maintenance of conditional matching and iteration is handled by list comprehension. 

Code:

# Python3 code to demonstrate how it works
# Preceding tuple elements in the list
# using zip () + list comprehension

 
# initialize the list

test_list = [ 1 , 4 , 'gfg' , 7 , 8 , ' gfg' , 9 , ' gfg' ]

 
# print original list

print ( "The original list is:" + str ( test_list))

 
# initialize ele

ele = 'gfg'

 
# Preceding tuple items in the list
# using zip () + list comprehension

res = [(x, y) for x, y in zip (test_list, test_list [ 1 : ]) if y = = ele]

  
# print result

print ( " Tuple list with desired Preceding elements " + str (res ))

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')] 




Get Solution for free from DataCamp guru