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!

1

2 Answers 2

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

Comments

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

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.