Python | Concatenate consecutive strings of characters in a list



Method # 1: Using List Comprehension + zip()
A combination of the above functions can be used to solve this problem. In this we iterate over the list using a list comprehension and pairing using zip ().

# Python3 code to demonstrate how it works
# Consecutive pairing of items in a list
# using a list comprehension + zip ()

 
# initialize the list

test_list = [ "G" , "F" , "G" , "I" , "S" , "B" ,   "E" , "S" , "T" ]

 
# print the original list

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

 
# Consecutive pairing of elements in a list
# using a list comprehension + zip ()

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

 
# print result

print ( "List after Consecutive concatenation is:" + str (res))

Output:

The original list: [`G`, `F`, `G` , `I`, `S`, `B`, `E`, `S`, `T`]
List after Consecutive concatenation is: [`GF`, `FG`, `GI`, `IS `,` SB `,` BE `,` ES `,` ST `]

Method # 2: Using map () + concat ()
A combination of these functions can accomplish this task as well. With this, the traversal logic is executed by map () and concat performs the pairing task. This is a more efficient method than the one above.

# Python3 code to demonstrate how it works
# Consecutive pairing of elements in the list
# using map () + concat

import operator

 
# initialize the list

test_list = [ "G" , "F" , "G" , "I" , "S" , "B " , "E" , "S " , " T " ]

 
# print original list

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

 
# Consecutive concatenation of elements in the list
# using map () + concat

res = list ( map (operator.concat, test_list [: - 1 ], test_list [ 1 :] ))

 
# print result

print ( "List after Consecutive concatenation is:" + str (res))

Output:

The original list: [`G`, `F`, ` G `,` I `,` S `,` B `,` E `,` S `,` T `]
List after Consecutive concatenation is: [` GF `,` FG `,` GI `, `IS`, `SB`, `BE`, `ES`, `ST`]