Python | Sequential string comparison

Method # 1: Using zip () + loop
This is one way to accomplish this task. In this we use zip () to concatenate an item and its next item, and then compare for the truth and store it in the list.

# Python3 demo code work
# Consecutive string comparison
# using zip () + loop

 
# initialize the list

test_list = [ ` gfg` , `gfg` , ` is` , `best` , ` best` , `for` , `geeks` , ` geeks ` ]

  
# print original list

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

 
# Consecutive string comparison
# using zip () + loop

res = []

for i, j in zip (test_list, test_list [ 1 :]):

  if i = = j:

res.append (i)

  
# print result

print ( " List of Consecutive similar elements: " + str (res))

Exit :

 The original list: [`gfg`,` gfg`, `is`,` best`, `best`,` for`, `geeks`,` geeks`] List of Consecutive similar elements: [`gfg`,` best`, `geeks`] 

Method # 2: Using comprehension list + zip ()
This task can also be done with using the above functions. In this, we take a one-liner approach to solve this problem using a list comprehension. The method is the same as above.

# Python3 code to demonstrate how it works
# Consecutive string comparison
# using zip () + list comprehension

 
# initialize the list

test_list = [ `gfg` , ` gfg ` , ` is` , `best` , ` best` , `for` , ` geeks` , `geeks` ]

  
# printing the original list

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

 
# Consecutive string comparison
# using zip () + list comprehension

res = [i for (i, j) in zip (test_list, test_list [ 1 :]) if i = = j]

 
# print result

print ( "List of Consecutive similar elements:" + str (res))

Output:

 The original list: [`gfg`,` gfg`, `is`,` best`, `best`,` for`, `geeks `,` geeks`] List of Consecutive similar elements: [`gfg`,` best`, `geeks`]