3

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?

3 Answers 3

5

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']
Sign up to request clarification or add additional context in comments.

Comments

1
o = ["prefix_" + str(i+1) for i in range(len(elements))]

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.