+1 vote
in Programming Languages by (74.2k points)
I want to add a prefix to all elements of a list. The list of the element numbers.

How can I do it?

e.g.

From

a=[10, 20, 30, 40]

to

['n_10', 'n_20', 'n_30', 'n_40']

1 Answer

+2 votes
by (350k points)
selected by
 
Best answer

You can iterate over the list to add a prefix to all of its elements. Since you want to add a string as the prefix, the resulting list will contain strings instead of numbers.

Here is an example:

>>> a=[10, 20, 30, 40]
>>> a=['n_' + str(j) for j in a]
>>> a
['n_10', 'n_20', 'n_30', 'n_40']
 


...