1

So I have a list like:

    L = ['a', 'b', 'c', 'd']

and

    for x in L:
        print(x)

returns

    'a'
    'b'
    'c'
    'd'

but I would like to see

    1. 'a'
    2. 'b'
    3. 'c'
    4. 'd'

I would like to have this work for any size the list might grow or shrink to. I have tried a few things but I am very new to programming and nothing has worked.

2

1 Answer 1

5

Use enumerate

for i, x in enumerate(L):
    print('{0}. {1}'.format(i, repr(x)))
Sign up to request clarification or add additional context in comments.

6 Comments

Using repr will not give the same result. print uses str
I'm not sure what you mean. I used repr because otherwise it won't include the quotes.
I see. I'm not sure if that's what he wants, however, because his original would not include the quotation marks. I could go either way on that.
Thank you Brendan. And thank you zondo, I just changed repr to str
Brendan, I looked on python.org at enumerate because I wanted to learn more. But it didn't answer a question I have about the way you printed it. in the beginning the {0}. {1} what exactly does that do?
|

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.