Search code examples
pythonlistcopy

Concatenate string to list of numbers repeating the string each time (Python)


I have a list of numbers, [0,1,2,3,4,5,6,7,8,9] and I would like to attach the word foo in front of each number to get a string each time to get

['foo0','foo1','foo2','foo3','foo4',
 'foo5','foo6','foo7','foo8','foo9']

a function like paste0('foo',0:9) in R.


Solution

  • Using list comprehension (credit: Barmar): ['foo' + str(i) for i in range(9)]

    Using map: list(map(lambda i: 'foo' + str(i), range(9)))

    Using f-strings: [f'foo{i}' for i in range(9)]