Open In App

Python | Concatenate N consecutive elements in String list

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with data, we can have a problem in which we need to perform the concatenation of N consecutive Strings in a list of Strings. This can have many applications across domains. Let’s discuss certain ways in which this task can be performed. 

Method #1: Using format() + zip() + iter() + list comprehension

The combination of the above methods can be used to perform this particular task. In this, we perform the task of grouping using zip() and iter(), format() is used to specify the grouping delimiter.

Python3




# Python3 code to demonstrate working of
# Consecutive N concatenation in String list
# using format() + zip() + iter() + list comprehension
 
# initialize list
test_list = ['gfg', 'is', 'good', 'for', 'geek', 'people']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize N
N = 3
 
# Consecutive N concatenation in String list
# using format() + zip() + iter() + list comprehension
temp = '{} ' * N
res = [temp.format(*ele) for ele in zip(*[iter(test_list)] * N)]
 
# printing result
print("List after N concatenation of String : " + str(res))


Output : 

The original list : ['gfg', 'is', 'good', 'for', 'geek', 'people']
List after N concatenation of String : ['gfg is good ', 'for geek people ']

Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using format() + zip() + iter() + list comprehension which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.

Method #2: Using starmap() + zip() + iter() + format()

The combination of the above functions performs a similar task. The only difference is that starmap() is used instead of list comprehension for list construction.

Python3




# Python3 code to demonstrate working of
# Consecutive N concatenation in String list
# using starmap() + zip() + iter() + format()
from itertools import starmap
 
# initialize list
test_list = ['gfg', 'is', 'good', 'for', 'geek', 'people']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize N
N = 3
 
# Consecutive N concatenation in String list
# using starmap() + zip() + iter() + format()
temp = '{} ' * N
res = list(starmap(temp.format, zip(*[iter(test_list)] * N)))
 
# printing result
print("List after N concatenation of String : " + str(res))


Output : 

The original list : ['gfg', 'is', 'good', 'for', 'geek', 'people']
List after N concatenation of String : ['gfg is good ', 'for geek people ']

Time complexity: O(n*n), where n is the length of the numbers list. The starmap() + zip() + iter() + format() have a time complexity of O(n)

Auxiliary Space: O(n), as we create new list res where n is the length of the numbers list.

Method #3 : Using map() , list slicing and join()

Python3




# Python3 code to demonstrate working of
# Consecutive N concatenation in String list
# using map() and join()
 
# initialize list
test_list = ['gfg', 'is', 'good', 'for', 'geek', 'people']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize N
N = 3
 
# Consecutive N concatenation in String list
# using map() and join()
result = list(map(' '.join, [test_list[i:i+N]
                             for i in range(0, len(test_list), N)]))
 
# printing result
print("List after N concatenation of String : " + str(result))
 
# this code is contributed by edula vinay kumar reddy


Output

The original list : ['gfg', 'is', 'good', 'for', 'geek', 'people']
List after N concatenation of String : ['gfg is good', 'for geek people']

This approach also uses map() and join() method to concatenate N consecutive strings in the list of strings. It iterates through the list by N steps and joins the slice of length N using map() method.

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4: Using a for loop and string concatenation

Python3




# Initialize the list
test_list = ['gfg', 'is', 'good', 'for', 'geek', 'people']
 
# Initialize N
N = 3
 
# Initialize the empty string
temp = ""
res = []
# Iterate over the list
for i in range(0, len(test_list), N):
    for j in range(N):
        if (i+j) < len(test_list):
            temp += test_list[i+j] + " "
    temp = temp.strip()
    res.append(temp)
    temp = ""
 
# Print the result
print(res)
# This code is contributed Vinay Pinjala.


Output

['gfg is good', 'for geek people']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #5: Using more_itertools chunked:

This is a Python program that defines a function named concat_n_consecutive which takes two arguments: test_list and n. test_list is a list of strings, and n is an integer that specifies the number of consecutive strings to concatenate together. The function uses the chunked method from the more_itertools library to split the test_list into chunks of n elements. Then, the function joins the elements of each chunk into a single string using a list comprehension. The function returns a list of concatenated strings.

The program then initializes a test list and an integer N, calls the concat_n_consecutive function with these inputs, and stores the result in a variable called result. Finally, the program prints the resulting list of concatenated strings using the print() function.

Python3




import more_itertools
# Function to concatenate n consecutive strings from the list
 
 
def concat_n_consecutive(test_list, n):
    # Using the `chunked` method from the `more_itertools` library to split the list into chunks of n elements
    # The `chunked` method returns a list of chunks, each chunk being a list of n elements
    # Using a list comprehension to join the elements of each chunk into a single string
    return [''.join(i) for i in more_itertools.chunked(test_list, n)]
 
 
# Initializing the test list and n
test_list = ['gfg', 'is', 'good', 'for', 'geek', 'people']
N = 3
# Calling the function
result = concat_n_consecutive(test_list, N)
# Printing the result
print("List after N concatenation of String:", result)
# This code is contributed by Jyothi pinjala.


Output:

List after N concatenation of String: [‘gfgisgood’, ‘forgeekpeople’] 

Time complexity of this code refers to the amount of time the program takes to execute as the size of the input data increases. It is O(n * m), which means the execution time grows in proportion to the length of the input list and the number of strings to concatenate.

Space complexity of this code refers to the amount of memory the program uses as the size of the input data increases. It is O(n+m), which means the memory usage grows in proportion to the length of the input list and the number of strings to concatenate.

Method#6: Using Recursive method

The group_words function takes the test_list and N as arguments, and recursively groups the words in the list into sub-lists of size N or smaller.

If the length of the input list is less than or equal to N, it simply returns a single sub-list that contains all the words in the input list.

Otherwise, it splits the input list into two parts: the first N words, and the rest of the list. It then recursively applies the same process to the rest of the list and combines the resulting sub-lists with the first N words as the first sub-list. Finally, it returns the list of sub-lists as the output.

Note: In the recursive case, the join method is used to combine the words in each sub-list into a single string.

Python3




def group_words(test_list, N):
    if len(test_list) <= N:
        return [' '.join(test_list)]
    else:
        return [ ' '.join(test_list[:N])] + group_words(test_list[N:], N)
     
# Test the recursive function
test_list = ['gfg', 'is', 'good', 'for', 'geek', 'people']
N = 3
res = group_words(test_list, N)
print(res)


Output

['gfg is good', 'for geek people']

Time complexity: O(n)
Where n is the length of the input list test_list. In each recursive call, we slice the input list into two parts, which takes O(n) time in the worst case. We then make one recursive call with the second part of the list, which has a length at most n-N, and concatenate the first N words of the original list to the result of the recursive call. The concatenation operation takes O(N) time, which is constant with respect to n. Since the recursion tree has depth n/N in the worst case, the total number of recursive calls is n/N, so the overall time complexity is O(n * (n/N)) = O(n^2/N).

Auxiliary Space: O(n)
Since the recursion tree has depth n/N in the worst case, each recursive call creates a new list that can contain up to N words. Therefore, the maximum space required by the recursive calls is O(n/N * N) = O(n). In addition, each list concatenation operation creates a new string that can contain up to N words, so the maximum space required by the concatenation operations is also O(n).



Previous Article
Next Article

Similar Reads

Python - Concatenate consecutive elements in Tuple
Sometimes, while working with data, we can have a problem in which we need to find cumulative results. This can be of any type, product, or summation. Here we are gonna discuss adjacent element concatenation. Let’s discuss certain ways in which this task can be performed. Method #1 : Using zip() + generator expression + tuple() The combination of a
4 min read
Python program to Concatenate all Elements of a List into a String
Given a list, the task is to write a Python program to concatenate all elements in a list into a string i.e. we are given a list of strings and we expect a result as the entire list is concatenated into a single sentence and printed as the output. Examples: Input: ['hello', 'geek', 'have', 'a', 'geeky', 'day'] Output: hello geek have a geeky dayUsi
3 min read
Python - Concatenate Rear elements in Tuple List
Given a tuple list where we need to concatenate rear elements. Input : test_list = [(1, 2, "Gfg"), ("Best", )] Output : Gfg Best Explanation : Last elements are joined. Input : test_list = [(1, 2, "Gfg")] Output : Gfg Explanation : Last elements are joined. Method #1 : Using list comprehension + join() In this, we check for last element using "-1",
6 min read
Python - Concatenate String values in Dictionary List
Sometimes, while working with Python records data, we can have a problem in which we require to perform concatenation of string values of keys by matching at particular key like ID. This kind of problem can have application in web development domain. Let's discuss certain way in which this task can be performed. Input : test_list = [{'id': 17, 'gfg
4 min read
Python - Concatenate Ranged Values in String list
Given list of strings, perform concatenation of ranged values from the Strings list. Input : test_list = ["abGFGcs", "cdforef", "asalloi"], i, j = 3, 5 Output : FGorll Explanation : All string sliced, FG, or and ll from all three strings and concatenated. Input : test_list = ["aGFGcs", "cforef", "aalloi"], i, j = 1, 4 Output : GFGforall Explanation
5 min read
Python - Concatenate Random characters in String List
Given a String list, perform concatenation of random characters. Input : test_list = ["Gfg", "is", "Best", "for", "Geeks"] Output : "GiBfe" Explanation : Random elements selected, e.g G from Gfg, etc.Input : test_list = ["Gfg", "is", "Best"] Output : "fst" Explanation : Random elements selected, e.g t from Best, etc. Method #1 : Using loop + random
6 min read
Python - Concatenate Tuple elements by delimiter
Given a tuple, concatenate each element of tuple by delimiter. Input : test_tup = ("Gfg", "is", 4, "Best"), delim = ", " Output : Gfg, is, 4, Best Explanation : Elements joined by ", ". Input : test_tup = ("Gfg", "is", 4), delim = ", " Output : Gfg, is, 4 Explanation : Elements joined by ", ". Method #1 : Using list comprehension In this, we iterat
7 min read
Python program to concatenate every elements across lists
Given 2 lists, perform concatenations of all strings with each other across list. Input : test_list1 = ["gfg", "is", "best"], test_list2 = ["love", "CS"] Output : ['gfg love', 'gfg CS', 'is love', 'is CS', 'best love', 'best CS'] Explanation : All strings are coupled with one another. Input : test_list1 = ["gfg", "best"], test_list2 = ["love", "CS"
4 min read
Python - Concatenate Kth element in Tuple List
While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data in concatenated format. Lets discuss certain ways how one can achieve solutions to this problem. Method #
8 min read
Python - Concatenate values with same keys in a list of dictionaries
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform concatenation of all the key values list that is like in dictionary list. This is quite a common problem and has applications in domains such as day-day programming and web development domain. Let's discuss the certain ways in which this task can be
7 min read
Practice Tags :
three90RightbarBannerImg