Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list of strings with fixed prefix based on size of a list

I want to create a list of strings with a fixed prefix where the suffix is based on the size of a list, by using python 3.3.2.

For example I have a list elements with len(elements) equal to 3. The output should be a list output = ['prefix_1','prefix_2','prefix_3']

I can do this by using a loop:

elements = ['elem1','elem2','elem3']
output = []
for i in range(len(elements)):
    output.append('prefix_'+str((i+1)))

This works but seems a bit... unpythonic to me. Is there a more pythonic way to do this? For example with a list comprehension?

like image 649
Tim Avatar asked Jan 29 '26 11:01

Tim


1 Answers

Using enumerate, str.format:

>>> elements = ['elem1','elem2','elem3']
>>> output = ['prefix_{}'.format(i) for i, elem in enumerate(elements, 1)]
>>> output
['prefix_1', 'prefix_2', 'prefix_3']
like image 56
falsetru Avatar answered Feb 01 '26 02:02

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!