Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend the same string to all items in a list

Tags:

Have done some searching through Stack Exchange answered questions but have been unable to find what I am looking for.

Given the following list:

a = [1, 2, 3, 4]

How would I create:

a = ['hello1', 'hello2', 'hello3', 'hello4']

Thanks!

like image 385
Fusilli Jerry Avatar asked Nov 11 '12 13:11

Fusilli Jerry


People also ask

How do you add a string to every element in a list Python?

We can use format() function which allows multiple substitutions and value formatting. Another approach is to use map() function. The function maps the beginning of all items in the list to the string.

Can you prepend to a list in Python?

To prepend to a list in Python, use the list. insert() method with index set to 0, which adds an element at the beginning of the list. The insert() is a built-in Python function that inserts an item to the list at the given index.

Can you use += to append a list?

For a list, += is more like the extend method than like the append method. With a list to the left of the += operator, another list is needed to the right of the operator. All the items in the list to the right of the operator get added to the end of the list that is referenced to the left of the operator.


2 Answers

Use a list comprehension:

[f'hello{i}' for i in a]

A list comprehension lets you apply an expression to each element in a sequence. Here that expression is a formatted string literal, incorporating i into a string starting with hello.

Demo:

>>> a = [1,2,3,4]
>>> [f'hello{i}' for i in a]
['hello1', 'hello2', 'hello3', 'hello4']
like image 92
Martijn Pieters Avatar answered Sep 22 '22 06:09

Martijn Pieters


One more option is to use built-in map function:

a = range(10)
map(lambda x: 'hello%i' % x, a)

Edit as per WolframH comment:

map('hello{0}'.format, a)
like image 11
Artsiom Rudzenka Avatar answered Sep 25 '22 06:09

Artsiom Rudzenka