Search code examples
pythonstringlistconcatenationprefix

Python adding prefix to list elements in python


I have this list of strings

lst = ["/foo/dir/c-.*.txt","/foo/dir2/d-.*.svc","/foo/dir3/es-.*.info"]

and I have a prefix string :

/root

Is there any pythonic way to add the prefix string to each element in the list, so the end result will look like this:

lst = ["/root/foo/dir/c-.*.txt","/root/foo/dir2/d-.*.svc","/root/foo/dir3/es-.*.info"]

If it can be done without iterating and creating new list ...


Solution

  • I am not sure of pythonic, but this will be also on possible way

    list(map(lambda x: '/root' + x, lst))
    

    Here there is comparison between list comp and map List comprehension vs map

    Also thanks to @chris-rands learnt one more way without lambda

    list(map('/root'.__add__, lst))