0

I'm trying to print a list of objects 1 by one and at the same time print count next to them.

Add something to the code so

for i in items:
    print(i)

returns:

  1. wool

  2. honey

    etc.

Community
  • 1
  • 1
maxintos
  • 25
  • 4

5 Answers5

3

The function you are looking for is enumerate

for idx, val in enumerate(items, 1):
    print(idx + '. ' + val)

As suggested by Harvey, enumerate returns a tuple, but str.join only accepts str iterables. If you were iterating over an indexable object whose keys and values were all strings (e.g. a str to str dict), then the code

for idx_val_pair in enumerate(items, 1):
    print('. '.join(idx_val_pair))

would also work.

EDIT: If you're just starting out with Python (which I suppose is the case) then don't worry about the stuff down here, but if you want to keep performance consistence among PyPy and CPython (among others) string concatenation is better done with the join method. The "correct" version of the code above would be

for idx, val in enumerate(items, 1):
    print('. '.join([str(idx), str(val)])
2

enumerate gives you the index of the current item returned.

You can use it like this:

# enumerate items, but start counting at 1
for i, j in enumerate(items, 1):
  print("{0}. {1}".format(i, j))

Here's an example usage:

>>> items = ["wool", "honey", "string"]
>>> for i, j in enumerate(items, 1):
...   print("{0}. {1}".format(i, j))
... 
1. wool
2. honey
3. string
erip
  • 13,935
  • 9
  • 51
  • 102
1
for count, label in enumerate(ls, 1):
    print '%d. %s' % (count, label)

Will produce desired output.

Dharmraj
  • 566
  • 5
  • 26
0

How about:

for j in range(len(items)):
    print("%d. %s" % (j+1, items[j]))
aghitza
  • 176
  • 3
0

This is done in python 2.7 and above answers gives already a good solution. As a python beginner I would start with something as simple solution as this. Printing can always be in prettier format, but just to give an idea.

    ls = ['wool','honey','extra']
    count = 0
        for l in ls:
        count+=1
        print str(count)+ '. ' + l

OR like suggested enumerate seems to be the best option

    for count, names in enumerate(ls, start=1): #start =   can be removed
        print str(count)+ '. ' + names
vento
  • 21
  • 3