Skip to content
Related Articles

Related Articles

Python | Insert the string at the beginning of all items in a list

View Discussion
Improve Article
Save Article
  • Last Updated : 15 Sep, 2022
View Discussion
Improve Article
Save Article

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




# Python3 program to insert the string
# at the beginning of all items in a list
 
 
def prepend(list, str):
 
    # Using format()
    str += '{0}'
    list = [str.format(i) for i in list]
    return(list)
 
 
# Driver function
list = [1, 2, 3, 4]
str = 'Geek'
print(prepend(list, str))

Output

['Geek1', 'Geek2', 'Geek3', 'Geek4']

Another method in list comprehension is to use ‘%’ instead of format() function 

Python3




# Using '% s'
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




# Python3 program to insert the string
# at the beginning of all items in a list
 
 
def prepend(List, str):
 
    # Using format()
    str += '{0}'
    List = ((map(str.format, List)))
    return List
 
 
# Driver function
list = [1, 2, 3, 4]
str = 'Geek'
print(prepend(list, str))

Output

<map object at 0x7f9f83334dd0>

They are as follows: 

['Geek1', 'Geek2', 'Geek3', 'Geek4']

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!