Home > Blockchain >  Print out the content of the list with order number in the front
Print out the content of the list with order number in the front

Time:11-23

I'm wondering if I have a list such as

['Jim', 'Nora', 'Jacob', 'May']

but I actually have a really long list (more than 300 items in it) and my desired output is something like this:

1. Jim
2. Nora
3. Jacob
4. May

Print out all the items in the list with the order number (start from 1, and the "." after the number is required) in the list (no hard-coding). How can I achieve this? Thank you!

CodePudding user response:

A list compression approach, if you actually need the entire output string as a single piece:

inp = ['Jim', 'Nora', 'Jacob', 'May']
output = '\n'.join([str(x 1)   '. '   inp[x] for x in range(len(inp))])
print(output)

This prints:

1. Jim
2. Nora
3. Jacob
4. May

CodePudding user response:

names = ['Jim', 'Nora', 'Jacob', 'May']
for idx, name in enumerate(names):
    print(f"{idx 1}. {name}")

Edit: Or the cleaner:

names = ['Jim', 'Nora', 'Jacob', 'May']
for idx, name in enumerate(names, start=1):
    print(f"{idx}. {name}")

CodePudding user response:

You can use a list enumerate.

lst = ['Jim', 'Nora', 'Jacob', 'May']
for number, name in enumerate(lst,1):
    print(str(number) '.', name)

[Output]

1. Jim
2. Nora
3. Jacob
4. May
  • Related