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:

``````>>1
>>2
>>3``````

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.

## All 3 Replies

Hi!

``````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.

No.

Regards, mawe

wonderful. thx

There is a discussion of how C and Python handle integers, and explains why n++ does not make sense in Python. See:
http://www.daniweb.com/tutorials/tutorial32575.html

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.