Open In App

Python – String Repetition and spacing in List

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

Sometimes while working with Python, we can have a problem in which we need to perform the repetition of each string in list and also attach a deliminator to each occurrence. This kind of problem can occur in day-day programming. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop 
This task can be performed in brute force way using loop. In this, we iterate the list and perform string addition and multiplication while iteration using suitable operators.

Python3




# Python3 code to demonstrate working of
# String Repetition and spacing in List
# Using loop
 
# initializing list
test_list = ['gfg', 'is', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = '-'
 
# initializing K
K = 3
 
# String Repetition and spacing in List
# Using loop
res = []
for sub in test_list:
    res.append((sub + delim) * K)
     
# printing result
print("List after performing operations : " + str(res))


Output : 

The original list is : ['gfg', 'is', 'best']
List after performing operations : ['gfg-gfg-gfg-', 'is-is-is-', 'best-best-best-']

 

Time complexity: O(n), where n is the length of the input list, because we loop through each element of the list once.
Auxiliary space: O(n), because we create a new list of length n to store the results.

 
Method #2 : Using join() + list comprehension 
The combination of above functionalities can also be used to perform this task. In this, we perform the task of attaching delim using join() and list comprehension performs the task of repetition. Avoids trailing delim.

Python3




# Python3 code to demonstrate working of
# String Repetition and spacing in List
# Using join() + list comprehension
 
# initializing list
test_list = ['gfg', 'is', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = '-'
 
# initializing K
K = 3
 
# String Repetition and spacing in List
# Using join() + list comprehension
res = []
for sub in test_list:
    res.append(delim.join([sub for _ in range(K)]))
     
# printing result
print("List after performing operations : " + str(res))


Output : 

The original list is : ['gfg', 'is', 'best']
List after performing operations : ['gfg-gfg-gfg', 'is-is-is', 'best-best-best']

 

Time complexity: O(n*K), where n is the length of the input list and K is the repetition factor.
Auxiliary space: O(n*K), as we are creating a new list with K repetitions of each element in the input list.

Method #3: Using itertools.repeat() 

Here’s an example of using itertools.repeat() to repeat each string in the list test_list and attach a delimiter to each occurrence:

Step-by-step approach:

  • Initializes an empty list res.
  • Iterates over each element in the test_list using a for loop.
  • For each element, it creates a list with K number of repetitions of the element using the itertools.repeat() function and then joins them with the delim separator using the join() method of strings. The resulting string is then appended to the res list.
  • Prints the resulting list res using the print() function and string concatenation.

Below is the implementation of the above approach:

Python3




import itertools
 
# initializing list
test_list = ['gfg', 'is', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = '-'
 
# initializing K
K = 3
 
# String Repetition and spacing in List
# Using itertools.repeat()
res = []
for sub in test_list:
    res.append(delim.join(list(itertools.repeat(sub, K))))
 
# printing result
print("List after performing operations : " + str(res))
 
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list is : ['gfg', 'is', 'best']
List after performing operations : ['gfg-gfg-gfg', 'is-is-is', 'best-best-best']

Time complexity: O(n * K) where n is the length of the list test_list and K is the number of repetitions.
Auxiliary Space: O(n * K) as we are creating a list of length n * K to store the results.

Method 4: Using map() and lambda functions.

Step-by-step approach:

  • Initialize the list of strings to be repeated.
  • Initialize the delimiter to be used for the repetition of strings.
  • Initialize the value of K, the number of times a string should be repeated.
  • Create a lambda function that takes a string as input and returns the string repeated K times, separated by the delimiter.
  • Use map() function to apply the lambda function to each string in the input list.
  • Convert the output of map() function to a list.
  • Print the final list after performing the operations.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# String Repetition and spacing in List
# Using map() and lambda functions
 
# initializing list
test_list = ['gfg', 'is', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = '-'
 
# initializing K
K = 3
 
# String Repetition and spacing in List
# Using map() and lambda functions
res = list(map(lambda x: delim.join([x]*K), test_list))
 
# printing result
print("List after performing operations : " + str(res))


Output

The original list is : ['gfg', 'is', 'best']
List after performing operations : ['gfg-gfg-gfg', 'is-is-is', 'best-best-best']

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n) as we are storing the output in a list.

Method 5: Using numpy.tile() and numpy.ravel()

Step-by-step approach:

  1. Import the numpy module.
  2. Initialize the list test_list.
  3. Print the original list.
  4. Initialize the delimiter delim and the number of repetitions K.
  5. Use a list comprehension to create a new list res with the repeated and spaced strings. The expression inside the brackets uses numpy.tile() to repeat each string in test_list K times vertically and 1 time horizontally, and numpy.ravel() to flatten the resulting 2D array into a 1D array. The join() method is then used to concatenate the resulting array of strings with the delimiter delim.
  6. Print the resulting list.

Python3




import numpy as np
 
# initializing list
test_list = ['gfg', 'is', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = '-'
 
# initializing K
K = 3
 
# String Repetition and spacing in List
# Using numpy.tile() and numpy.ravel()
res = [delim.join(np.ravel(np.tile([x], (K, 1)))) for x in test_list]
 
# printing result
print("List after performing operations : " + str(res))


OUTPUT:

The original list is : ['gfg', 'is', 'best']
List after performing operations : ['gfg-gfg-gfg', 'is-is-is', 'best-best-best']

Time complexity: The time complexity of this method is O(nk), where n is the length of the input list test_list and k is the number of repetitions K, since the operation of repeating each string in test_list K times has a time complexity of O(k|s|), where |s| is the length of the string.

Auxiliary space: The auxiliary space used by this method is O(nk), since a new list of size n*k is created.

Method 6: Using list multiplication and string concatenation

Step-by-step approach:

  • Define the delimiter string delim and the integer K representing the number of times each string should be repeated.
  • Create a new list res using a list comprehension that multiplies each string in test_list by K, concatenates K-1 instances of the delimiter delim between them using the string multiplication operator *, and finally appends the resulting string to res.
  • Print the result using the print() function and passing the string representation of res.

Below is the implementation of the above approach:

Python3




# Method 6: Using list multiplication and string concatenation
 
# initializing list
test_list = ['gfg', 'is', 'best']
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = '-'
 
# initializing K
K = 3
 
# String Repetition and spacing in List
# Using list multiplication and string concatenation
res = [delim.join([s] * K) for s in test_list]
 
# printing result
print("List after performing operations : " + str(res))


Output

The original list is : ['gfg', 'is', 'best']
List after performing operations : ['gfg-gfg-gfg', 'is-is-is', 'best-best-best']

 Time complexity: O(N * K), where N is the length of test_list.
Auxiliary space: O(N * K), where N is the length of test_list. This is because a new list of length N * K is created to store the result.



Previous Article
Next Article

Similar Reads

Python - Incremental and Cyclic Repetition of List Elements
Sometimes, while working with Python lists, we can have a problem in which we need to repeat elements K times. But we can have variations in this and have to repeat elements in cyclic and incremental way. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + enumerate() This is brute force way in which this task c
4 min read
Python | Element repetition in list
Sometimes we require to add a duplicate value in the list for several different utilities. This type of application is sometimes required in day-day programming. Let's discuss certain ways in which we add a clone of a number to its next position. Method #1: Using list comprehension In this method, we just iterate the loop twice for each value and a
8 min read
Randomly select elements from list without repetition in Python
Python's built-in module in random module is used to work with random data. The random module provides various methods to select elements randomly from a list, tuple, set, string or a dictionary without any repetition. Below are some approaches which depict a random selection of elements from a list without repetition by: Method 1: Using random.sam
3 min read
Python - Index Value repetition in List
Given a list of elements, The task is to write a Python program to repeat each index value as per the value in that index. Input : test_list = [3, 0, 4, 2] Output : [0, 0, 0, 2, 2, 2, 2, 3, 3] Explanation : 0 is repeated 3 times as its index value is 3. Input : test_list = [3, 4, 2] Output : [0, 0, 0, 1, 1, 1, 1, 2, 2] Explanation : 1 is repeated 4
7 min read
Python - Custom Consecutive character repetition in String
Given a String, repeat characters consecutively by number mapped in dictionary. Input : test_str = 'Geeks4Geeks', test_dict = {"G" : 3, "e" : 1, "4" : 3, "k" : 5, "s" : 3} Output : GGGeekkkkksss444GGGeekkkkksss Explanation : Each letter repeated as per value in dictionary.Input : test_str = 'Geeks4Geeks', test_dict = {"G" : 3, "e" : 1, "4" : 3, "k"
4 min read
Python - Character repetition string combinations
Given a string list and list of numbers, the task is to write a Python program to generate all possible strings by repeating each character of each string by each number in the list. Input : test_list = ["gfg", "is", "best"], rep_list = [3, 5, 2]Output : ['gggfffggg', 'iiisss', 'bbbeeesssttt', 'gggggfffffggggg', 'iiiiisssss', 'bbbbbeeeeesssssttttt'
3 min read
Python - Consecutive Repetition of Characters
Sometimes, while working with character lists we can have a problem in which we need to perform consecutive repetition of characters. This can have applications in many domains. Let us discuss certain ways in which this task can be performed. Method #1: Using list comprehension This is one of the way in which this task can be performed. In this, we
5 min read
Python - Custom element repetition
Given list of elements and required occurrence list, perform repetition of elements. Input : test_list1 = ["Gfg", "Best"], test_list2 = [4, 5] Output : ['Gfg', 'Gfg', 'Gfg', 'Gfg', 'Best', 'Best', 'Best', 'Best', 'Best'] Explanation : Elements repeated by their occurrence number. Input : test_list1 = ["Gfg"], test_list2 = [5] Output : ['Gfg', 'Gfg'
6 min read
How to set the spacing between subplots in Matplotlib in Python?
In this article, we will see how to set the spacing between subplots in Matplotlib in Python. Let's discuss some concepts : Matplotlib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. I
3 min read
PyQt5 – Add spacing between indicator and Check box
In this article we will see how to set spacing in between the check box and the indicator. When we create a check box by default some space in between them, but we change that space also. Below is the representation of default check box vs the increased spaced check box. This can be done by changing the size of spacing in the style sheet of check b
2 min read
Practice Tags :
three90RightbarBannerImg