Python | Concatenate N consecutive elements in String list
Last Updated :
13 Apr, 2023
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
test_list = [ 'gfg' , 'is' , 'good' , 'for' , 'geek' , 'people' ]
print ( "The original list : " + str (test_list))
N = 3
temp = '{} ' * N
res = [temp. format ( * ele) for ele in zip ( * [ iter (test_list)] * N)]
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
from itertools import starmap
test_list = [ 'gfg' , 'is' , 'good' , 'for' , 'geek' , 'people' ]
print ( "The original list : " + str (test_list))
N = 3
temp = '{} ' * N
res = list (starmap(temp. format , zip ( * [ iter (test_list)] * N)))
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
test_list = [ 'gfg' , 'is' , 'good' , 'for' , 'geek' , 'people' ]
print ( "The original list : " + str (test_list))
N = 3
result = list ( map ( ' ' .join, [test_list[i:i + N]
for i in range ( 0 , len (test_list), N)]))
print ( "List after N concatenation of String : " + str (result))
|
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
test_list = [ 'gfg' , 'is' , 'good' , 'for' , 'geek' , 'people' ]
N = 3
temp = ""
res = []
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 (res)
|
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
def concat_n_consecutive(test_list, n):
return [''.join(i) for i in more_itertools.chunked(test_list, n)]
test_list = [ 'gfg' , 'is' , 'good' , 'for' , 'geek' , 'people' ]
N = 3
result = concat_n_consecutive(test_list, N)
print ( "List after N concatenation of String:" , result)
|
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_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).
Similar Reads
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Get a list as input from user in Python
We often encounter a situation when we need to take a number/string as input from the user. In this article, we will see how to take a list as input from the user using Python. Get list as input Using split() MethodThe input() function can be combined with split() to accept multiple elements in a si
3 min read
Create List of Numbers with Given Range - Python
The task of creating a list of numbers within a given range involves generating a sequence of integers that starts from a specified starting point and ends just before a given endpoint. For example, if the range is from 0 to 10, the resulting list would contain the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8,
3 min read
Python - Add List Items
Python makes working with lists easy and one common operation is adding items to a list. Let's explore how to add items to a list in Python with some simple code examples. Adding a Single Item Using append()append() method adds a single item to the end of the list. [GFGTABS] Python li = [1, 2, 3] li
3 min read
How to add Elements to a List in Python
In Python, adding elements to a list is a common operation that can be done in several ways. One of the simplest methods is using the append() method. In this article we are going to explore different methods to add elements in the list. Below is a simple Python program to add elements to a list usi
3 min read
List Iteration Operations
Iterate over a list in Python
Python provides several ways to iterate over list. The simplest and the most common way to iterate over a list is to use a for loop. This method allows us to access each element in the list directly. Example: Print all elements in the list one by one using for loop. [GFGTABS] Python a = [1, 3, 5, 7,
3 min read
How to iterate through a nested List in Python?
A nested list is a list that contains other lists. Working with nested lists can seem tricky at first but it becomes easy once we understand how to iterate through them. This is the easiest way to loop through a nested list. We can use a for loop to access each sublist in the main list, and then use
3 min read
Python | Iterate over multiple lists simultaneously
Iterating over single lists, refers to using for loops for iteration over a single element of a single list at a particular step whereas in iterating over multiple lists simultaneously, we refer using for loops for iteration over a single element of multiple lists at a particular step. Iterate over
4 min read
Iterate Over a List of Lists in Python
Iterating over a list of lists is a common task in Python, especially when dealing with datasets or matrices. In this article, we will explore various methods and techniques for efficiently iterating over nested lists, covering both basic and advanced Python concepts. In this article, we will see ho
3 min read
Python List Search Operations
How To Find the Length of a List in Python
The length of a list refers to the number of elements in the list. There are several methods to determine the length of a list in Python. In this article, we'll explore different methods to find the length of a list. The simplest and most common way to do this is by using the len() function. Let's t
3 min read
Python | Find elements of a list by indices
Given two lists with elements and indices, write a Python program to find elements of list 1 at indices present in list 2. Examples: Input : lst1 = [10, 20, 30, 40, 50] lst2 = [0, 2, 4] Output : [10, 30, 50] Explanation: Output elements at indices 0, 2 and 4 i.e 10, 30 and 50 respectively. Input : l
5 min read
Python program to find String in a List
Searching for a string in a list is a common operation in Python. Whether we're dealing with small lists or large datasets, knowing how to efficiently search for strings can save both time and effort. In this article, weâll explore several methods to find a string in a list, starting from the most e
3 min read
Python - Ways to find indices of value in list
In Python, it is common to locate the index of a particular value in a list. The built-in index() method can find the first occurrence of a value. However, there are scenarios where multiple occurrences of the value exist and we need to retrieve all the indices. Python offers various methods to achi
3 min read
Python | Find most frequent element in a list
Given a list, find the most frequent element in it. If multiple elements appear a maximum number of times, print any one of them using Python. Example Make a set of the list so that the duplicate elements are deleted. Then find the highest count of occurrences of each element in the set and thus, we
2 min read
Python List Remove Operations
Python - Remove List Item
Removing List Item can be achieved using several built-in methods that provide flexibility in how you remove list items. In this article, we'll explore the different ways to remove list items in Python. Removing Item by Value with remove()The remove() method allows us to remove the first occurrence
3 min read
How to Remove Item from a List in Python
Lists in Python have various built-in methods to remove items such as remove, pop, del and clear methods. Removing elements from a list can be done in various ways depending on whether we want to remove based on the value of the element or index. The simplest way to remove an element from a list by
3 min read
Python | Remove given element from the list
Given a list, write a Python program to remove the given element (list may have duplicates) from the given list. There are multiple ways we can do this task in Python. Let's see some of the Pythonic ways to do this task. Example: Input: [1, 8, 4, 9, 2] Output: [1, 8, 4, 2] Explanation: The Element 9
7 min read
Ways to remove particular List element in Python
There are times when we need to remove specific elements from a list, whether itâs filtering out unwanted data, deleting items by their value or index or cleaning up lists based on conditions. In this article, weâll explore different methods to remove elements from a list. Using List ComprehensionLi
2 min read
Remove Multiple Elements from List in Python
In this article, we will explore various methods to remove multiple elements from a list in Python. The simplest way to do this is by using a loop. A simple for loop can also be used to remove multiple elements from a list. [GFGTABS] Python a = [10, 20, 30, 40, 50, 60, 70] # Elements to remove remov
3 min read
Python List Concatenation Operations
Python - Concatenate two lists element-wise
In Python, concatenating two lists element-wise means merging their elements in pairs. This is useful when we need to combine data from two lists into one just like joining first names and last names to create full names. zip() function is one of the most efficient ways to combine two lists element-
3 min read
Merge Two Lists in Python
Python provides several approaches to merge two lists. In this article, we will explore different methods to merge lists with their use cases. The simplest way to merge two lists is by using the + operator. Let's take an example to merge two lists using + operator. [GFGTABS] Python a = [1, 2, 3] b =
4 min read
Concatenate two list of lists Row-wise-Python
The task of concatenate two lists of lists row-wise, meaning we merge corresponding sublists into a single sublist. For example, given a = [[4, 3], [1, 2]] and b = [[7, 5], [9, 6]], we pair elements at the same index: [4, 3] from a is combined with [7, 5] from b, resulting in [4, 3, 7, 5], and [1, 2
3 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_l
4 min read
Concatenate all Elements of a List into a String - Python
We are given a list of words and our task is to concatenate all the elements into a single string with spaces in between. For example, given the list: li = ['hello', 'geek', 'have', 'a', 'geeky', 'day'] after concatenation, the result will be: "hello geek have a geeky day". Using str.join()str.join(
3 min read
Concatenate All Records - Python
The task of concatenating all records in Python involves combining elements from a list, typically strings, into a single unified string. The goal is to concatenate each individual element, ensuring that the result is a continuous string without spaces or delimiters, unless specified. For example, g
3 min read
Python - Merge list elements
Merging list elements is a common task in Python. Each method has its own strengths and the choice of method depends on the complexity of the task. This is the simplest and most straightforward method to merge elements. We can slice the list and use string concatenation to combine elements. [GFGTABS
2 min read
Python | Concatenate N consecutive elements in String list
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() + i
8 min read
Python | Merge two lists alternatively
Given two lists, write a Python program to merge the given lists in an alternative fashion, provided that the two lists are of equal length. Examples: Input : lst1 = [1, 2, 3] lst2 = ['a', 'b', 'c'] Output : [1, 'a', 2, 'b', 3, 'c'] Input : lst1 = ['name', 'alice', 'bob'] lst2 = ['marks', 87, 56] Ou
4 min read
Python - Union of two or more Lists
The union of two or more lists combines all elements ensuring no duplicates if specified. In this article we will explore various methods to get a union of two lists. Using set.union (Most Efficient for Uniqueness)The union() method ensures that the resulting list contains unique elements. Here we c
2 min read