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?
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With