2

How do I print out the index location of each of a python list so that it starts at 1, rather than 0. Here's an idea of what I want it to look like:

    blob = ["a", "b", "c", "d", "e", "f"]
    for i in blob:
        print(???)

Output:

1   a
2   b
3   c
4   d
5   e

What I need to know is how do I get those numbers to show up alongside what I'm trying to print out? I can get a-e printed out no problem, but I can't figure out how to number the list.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Fluxriflex
  • 78
  • 1
  • 1
  • 7

5 Answers5

15

You would need to enumerate your list. That means that for every letter, it has a corrosponding number.

Here is an example of your working code:

blob = ["a", "b", "c", "d", "e", "f"]

for number, letter in enumerate(blob):
    print(number, letter)

The enumerate function will give the variable number the position of the variable letter in your list every loop.

To display them, you can just use print(number, letter) to display them side by side.

Josh B.
  • 414
  • 5
  • 14
7
for a, b in enumerate(blob, 1):
    print '{} {}'.format(a, b)
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
1

Another solution using built-in operations:

Edit: In case you need extra space:

s1 = ['a', 'b', 'c', 'd']
for i in s1:
    print(s1.index(i) +1, end=' ')
    print(" ",i)

Output:

1   a
2   b
3   c
4   d
Niranjan M.R
  • 343
  • 1
  • 6
  • 23
1

You can use this one-liner.

print(list(enumerate(blob)))

to start with index 1

print(list(enumerate(blob, start=1)))

Codes above will print everthing in one line. If you want to print each element in a new line

from pprint import pprint  # no install required
pprint(list(enumerate(blob, start=1)), depth=2)
alercelik
  • 615
  • 7
  • 11
1

One-liner pretty printing of enumerate object:

myList = ['a', 'b', 'c']
print(*enumerate(myList), sep='\n')

Output:

(0, 'a')
(1, 'b')
(2, 'c')

If one want to control the output format use this (with your own formatting):

print('\n'.join(['{}-{}'.format(i, val) for i, val in (enumerate(myList))]))

Output:

0-a
1-b
2-c
itamar kanter
  • 1,170
  • 3
  • 10
  • 25