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.

Arkyris
  • 87
  • 12
  • look up [`enumerate()`](https://docs.python.org/3/library/functions.html#enumerate). – MattDMo Feb 05 '16 at 02:22
  • 1
    Possible duplicate of [Accessing the index in Python for loops](http://stackoverflow.com/questions/522563/accessing-the-index-in-python-for-loops) – MattDMo Feb 05 '16 at 02:23

1 Answers1

5

Use enumerate

for i, x in enumerate(L):
    print('{0}. {1}'.format(i, repr(x)))
Brendan Abel
  • 28,703
  • 11
  • 72
  • 95
  • Using `repr` will not give the same result. `print` uses `str` – zondo Feb 05 '16 at 02:24
  • I'm not sure what you mean. I used `repr` because otherwise it won't include the quotes. – Brendan Abel Feb 05 '16 at 02:27
  • 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. – zondo Feb 05 '16 at 02:30
  • Thank you Brendan. And thank you zondo, I just changed `repr` to `str` – Arkyris Feb 05 '16 at 02:35
  • 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? – Arkyris Feb 05 '16 at 02:43
  • It's part of python string formatting - https://docs.python.org/2/library/string.html#format-string-syntax – Brendan Abel Feb 05 '16 at 02:48