Fluxriflex
Fluxriflex

Reputation: 98

How to print out a numbered list in Python 3

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.

Upvotes: 3

Views: 50773

Answers (5)

itamar kanter
itamar kanter

Reputation: 1360

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

Upvotes: 3

alercelik
alercelik

Reputation: 723

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)

Upvotes: 3

Niranjan M.R
Niranjan M.R

Reputation: 351

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

Upvotes: 0

Josh B.
Josh B.

Reputation: 432

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.

Upvotes: 15

Malik Brahimi
Malik Brahimi

Reputation: 16711

for a, b in enumerate(blob, 1):
    print '{} {}'.format(a, b)

Upvotes: 6

Related Questions