Python | Insert the string at the beginning of all items in a list
Last Updated :
13 Mar, 2023
Given a list, write a Python program to insert some string at the beginning of all items in that list.
Examples:
Input : list = [1, 2, 3, 4], str = 'Geek'
Output : list = ['Geek1', 'Geek2', 'Geek3', 'Geek4']
Input : list = ['A', 'B', 'C'], str = 'Team'
Output : list = ['TeamA', 'TeamB', 'TeamC']
There are multiple ways to insert the string at the beginning of all items in a list.
Approach #1: Using list comprehension List comprehension is an elegant way to define and create list. It can also be used to apply an expression to each element in a sequence. We can use format() function which allows multiple substitutions and value formatting.
Python3
def prepend(list, str):
str += '{0}'
list = [str.format(i) for i in list]
return(list)
list = [1, 2, 3, 4]
str = 'Geek'
print(prepend(list, str))
Output
['Geek1', 'Geek2', 'Geek3', 'Geek4']
Time Complexity: O(n)Auxiliary Space: O(n), where n is length of list.
Another method in list comprehension is to use ‘%’ instead of format() function
Python3
def prepend(list, str):
str += '% s'
list = [str % i for i in list]
list = [1, 2, 3, 4]
str = 'Geek'
print(prepend(list, str))
Approach #2 : Using in-built map() function
Another approach is to use map() function. The function maps the beginning of all items in the list to the string.
Python3
def prepend(List, str):
str += '{0}'
List = ((map(str.format, List)))
return List
list = [1, 2, 3, 4]
str = 'Geek'
print(prepend(list, str))
Output
<map object at 0x7f9f83334dd0>
They are as follows:
['Geek1', 'Geek2', 'Geek3', 'Geek4']
Approach #3 : Using a for loop and + operator.
Here is another approach using a for loop to iterate through the elements in the list and concatenating the string and each element using the + operator.
Here is an example of how this approach could be implemented:
Python3
def prepend(lst, s):
res = []
for x in lst:
res.append(s + str(x))
return res
lst = [1, 2, 3, 4]
s = 'Geek'
print(prepend(lst, s))
Output
['Geek1', 'Geek2', 'Geek3', 'Geek4']
The time complexity is O(n), where n is the length of the list. This is because approach involve iterating through the elements in the list once. The space complexity is O(n), because it only creates a single list of size n to store the result.
Share your thoughts in the comments
Add Your Comment
Please Login to comment...