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).



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads