954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

iterators

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.

senateboy
Newbie Poster
5 posts since Jan 2006
Reputation Points: 10
Solved Threads: 0
 

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

mawe
Junior Poster
133 posts since Sep 2005
Reputation Points: 19
Solved Threads: 58
 

wonderful. thx

senateboy
Newbie Poster
5 posts since Jan 2006
Reputation Points: 10
Solved Threads: 0
 

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.

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You