Given list of strings, perform concatenation in groups till K.
Input : test_list = [“Gfg”, “is”, “Best”, “”, “I”, “Love”, “”, “Gfg”], K = “”
Output : [‘Gfg is Best’, ‘I Love’, ‘Gfg’]
Explanation : Concatenated words with “” as new String separator.Input : test_list = [“Gfg”, “is”, “Best”, “”, “I”, “Love”], K = “”
Output : [‘Gfg is Best’, ‘I Love’]
Explanation : Concatenated words with “” as new String separator.
Method : Using loop + join() + list comprehension
This is a way in which this task can be performed. In this, we construct parts of strings into lists, and then perform join of individual lists using join() and list comprehension.
Python3
# Python3 code to demonstrate working of # Group concatenate Till K # Using loop + join() + list comprehension # initializing lists test_list = ["Gfg", "is", "Best", None, "I", "Love", None, "Gfg"] # printing original list print("The original list : " + str(test_list)) # initializing K K = None # all() to encapsulate whole logic into one expression res = [[]] for sub in test_list: # checking for K value, and performing append to # latest list if sub != K: res[-1].append(sub) else: # constructing new list if new group res.append([]) # Joining all groups fin_res = [' '.join(ele) for ele in res] # printing result print("Concatenated Groups : " + str(fin_res)) |
The original list : ['Gfg', 'is', 'Best', None, 'I', 'Love', None, 'Gfg'] Concatenated Groups : ['Gfg is Best', 'I Love', 'Gfg']
Recommended Posts:
- Python | Pandas Series.str.cat() to concatenate string
- Python | Merge, Join and Concatenate DataFrames using Panda
- Python | Ways to concatenate two lists
- Python | Concatenate two lists element-wise
- Python program to concatenate Strings around K
- Python | Ways to concatenate boolean to string
- Python | Concatenate dictionary value lists
- Python | Ways to concatenate tuples
- Python | Numpy np.ma.concatenate() method
- Python | How to Concatenate tuples to nested tuples
- Python | Concatenate N consecutive elements in String list
- Python - Concatenate Kth element in Tuple List
- Python - Concatenate consecutive elements in Tuple
- Python | Concatenate All Records
- Python - Concatenate Dictionary string values
- Python program to concatenate two Integer values into one
- Python - Concatenate string rows in Matrix
- numpy.concatenate() function | Python
- Python - Concatenate values with same keys in a list of dictionaries
- Python - Concatenate String values in Dictionary List
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.

