how can i get the index number of a iterator? for instance:

i wante to return the number of times ive gone through the loop.

list = [(mark, jacky,jane),(stick,cheri,nice),(elly,younces,pluto)]
for i in list:
    print i

this returns lists. but i want an output like:


how do i do this withought making another variable and adding to it for each iteration through the loop.

also: is there a similar expression like C's" index++ " for python.

12 Years
Discussion Span
Last Post by vegaseat


lst = ["a","b","c"]

# the old method
for i in range(len(lst)):
    print i, lst[i]

# the new one (since Python 2.4)
for i, x in enumerate(lst):
    print i, x

also: is there a similar expression like C's" index++ " for python.


Regards, mawe


There is a discussion of how C and Python handle integers, and explains why n++ does not make sense in Python. See:

Editor's note: this tutorial has been send to the doghouse as utter kaka junk!

In your corrected code this would work fine ...

list = [('mark', 'jacky','jane'),('stick','cheri','nice'),('elly','younces','pluto')]
n = 0
for i in list:
    print n, i
    n += 1      # replaces C's n++

If you want to pick the list of tuples really appart, then use this ...

list = [('mark', 'jacky','jane'),('stick','cheri','nice'),('elly','younces','pluto')]
n = 0
for t in list:
    m = 0
    for i in t:
        print n, m, i
        m += 1
    n += 1
0 0 mark
0 1 jacky
0 2 jane
1 0 stick
1 1 cheri
1 2 nice
2 0 elly
2 1 younces
2 2 pluto

This gives you the index of the tuple, followed by the index in the tuple, then the value.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.