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

How can I do it?



a=[10, 20, 30, 40]


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

1 Answer

+2 votes
by (348k 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']