0

still pretty new to Python and programming in general. My current task is to print each item of a list on separate lines with an index identifier in front of it. E.g. My list is currently:

['Ada Log\n', 'Ena Blue\n', 'Kin Wall\n', 'Kin Wall\n', 'Foxy Rex\n', 'Esk Brown']

I want this to output as...

[1] Ada Log

[2] Ena Blue

[3] Kin Wall

[4] Foxy Rex

[5] Esk Brown

So that the numbers 1-5 can be used as a further input to produce more information. Thanks for any feedback.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
Djpopple
  • 31
  • 4
  • 1
    Does this answer your question? [Accessing the index in 'for' loops?](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – Aven Desta May 21 '21 at 04:15
  • You seem to have accidentally deleted much relevant information. I undid that for you. Please do not remove info after getting an answer. The question is supposed to stay answerable without knowing "the" answer. (If I misunderstood you and the reason for the edit, please consider providing a summary for your edits, which point out the reason. That way I might understand better. The editor provides a field to write something for that.) – Yunnosch May 25 '21 at 08:24

3 Answers3

3

Mmm, enumerate should do the trick.


names = ['Ada Log\n', 'Ena Blue\n', 'Kin Wall\n', 'Kin Wall\n', 'Foxy Rex\n', 'Esk Brown']
#Note second argument in enumerate tells us where to start
for count,name in enumerate(names,1):
    print(f'[{count}] {name}')

output

[1] Ada Log

[2] Ena Blue

[3] Kin Wall

[4] Kin Wall

[5] Foxy Rex

[6] Esk Brown
Buddy Bob
  • 5,829
  • 1
  • 13
  • 44
1

Using a list comprehension with enumeration:

inp = ['Ada Log\n', 'Ena Blue\n', 'Kin Wall\n', 'Foxy Rex\n', 'Esk Brown']
output = ''.join(['[' + str(ind + 1) + '] ' + x  for ind, x in enumerate(inp)])
print(output)

This prints:

[1] Ada Log
[2] Ena Blue
[3] Kin Wall
[4] Foxy Rex
[5] Esk Brown
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

Similar to @BuddyBob's solution:

names = ['Ada Log\n', 'Ena Blue\n', 'Kin Wall\n', 'Kin Wall\n', 'Foxy Rex\n', 'Esk Brown']
for count,name in enumerate(names, 1):
    print(f'[{count}] {name}')
Ralf Zosel
  • 683
  • 1
  • 7
  • 26