Related Articles

Related Articles

Python | Insert the string at the beginning of all items in a list
  • Last Updated : 20 Nov, 2019

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


 
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.

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']

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :