0

Using Python I want to print the elements of a list using for loop and also I want to generate a number for each item in the list. Something like an ID column next to the column containing the list's items.

Example:

lst = ['One', 'Two', 'Three']

for item in lst:
    print(item)

Result:

One
Two
Three

What I would like to print:

1 One
2 Two
3 Three

Thank you!

lyubol
  • 119
  • 9
  • Does this answer your question? [Get loop count inside a Python FOR loop](https://stackoverflow.com/questions/3162271/get-loop-count-inside-a-python-for-loop) – mkrieger1 Jul 25 '21 at 13:52

2 Answers2

0

You could use enumerate

lst = ['One', 'Two', 'Three']

for num,item in enumerate(lst,start=1):
    print(num,item)

Output:

1 One
2 Two
3 Three
0

You can try the built-in enumerate() method:

lst = ['One', 'Two', 'Three']

for i, item in enumerate(lst, 1):
    print(i, item)

Output:

1 One
2 Two
3 Three

A potential problem here is when the digits start becoming different lengths, like:

lst = ['One', 'Two', 'Three', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test']

Output:

1 One
2 Two
3 Three
4 test
5 test
6 test
7 test
8 test
9 test
10 test
11 test
12 test
13 test

where the starting point of each word doesn't align anymore. That can be fixed with the str.ljust() method:

lst = ['One', 'Two', 'Three', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test', 'test']

for i, item in enumerate(lst, 1):
    print(str(i).ljust(2), item)

Output:

1  One
2  Two
3  Three
4  test
5  test
6  test
7  test
8  test
9  test
10 test
11 test
12 test
13 test
Red
  • 26,798
  • 7
  • 36
  • 58