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

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Using '% s'
str += '% s'
list =  [str % i for i in list]

chevron_right


 
Appraoch #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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.