String Repetition and spacing in List - Python
Last Updated :
12 Jul, 2025
We are given a list of strings and our task is to modify it by repeating or adding spaces between elements based on specific conditions. For example, given the list `a = ['hello', 'world', 'python']`, if we repeat each string twice, the output will be `['hellohello', 'worldworld', 'pythonpython'].
Using List Comprehension
List comprehension allows us to modify each element in the list efficiently. We can repeat each string a fixed number of times or add spaces dynamically.
Python
# Repeat each string twice
a = ["hello", "world", "python"]
a = [x * 2 for x in a]
print(a)
Output['hellohello', 'worldworld', 'pythonpython']
Explanation:
- This method efficiently repeats each string using `x * 2`, which duplicates each element.
- It is useful when we want to repeat each string a fixed number of times.
Let's explore some more ways and see how we can perform string repetition and spacing in list.
Using join() for Spacing
We can use the join() method to combine list elements with a specific spacing between them.
Python
# Join list elements with 3 spaces in between
a = ["hello", "world", "python"]
res = " ".join(a)
print(res)
Explanation:
- The join() method efficiently inserts spaces between elements.
- This is useful when formatting strings with specific spacing.
Using for Loop
Using a for loop, we can manually repeat elements or add spaces dynamically based on conditions.
Python
# Repeat each string twice and add a space between repetitions
a = ["hello", "world", "python"]
b = []
for x in a:
b.append((x + " ") * 2)
print(b)
Output['hello hello ', 'world world ', 'python python ']
Explanation:
- This method provides more control over repetition and spacing.
- However, it is less efficient due to the use of a loop and repeated append operations.
Using map() with Lambda Function
map() function allows us to apply modifications to each element without using an explicit loop.
Python
# Repeat each string three times with a space in between
a = ["hello", "world", "python"]
a = list(map(lambda x: (x + " ") * 3, a))
print(a)
Output['hello hello hello ', 'world world world ', 'python python python ']
Explanation: map() function applies a transformation to each element.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice