Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through an enumerate object and print all the index-item pairs using next() function?

Tags:

python

I have the following program

enum1 = enumerate("This is the test string".split())

I need to iterate through enum1 and print all the index-item pairs by using next() function.

I try to get the index-item pairs by doing the following

for i in range(len(enum1)):
    print enum1.next()

It throws me an error showing len() can't be applied to an enumeration.

Could anyone suggest me any such way by which I would be able to iterate through this enum to print all the index-item pairs using next() function?

Note: My requirement is to use next() function to retrieve the index-item pairs


2 Answers

simply use:

for i,item in enum1:
   # i is the index
   # item is your item in enum1

or

for i,item in enumerate("This is the test string".split()):
   # i is the index
   # item is your item in enum1

this will use the next method underneath...

like image 87
rafalotufo Avatar answered Sep 21 '25 14:09

rafalotufo


Given the weird requirement that you need to use the next() method, you could do

try:
    while True:
        print enum1.next()
except StopIteration:
    pass

You don't know in advance how many items an iterator will yield, so you just have to keep trying to call enum1.next() until the iterator is exhausted.

The usual way to do this is of course

for item in enum1:
    print item

Furthermore, in Python 2.6 or above, calls to the next() method should be replaced by calls to the built-in function next():

print next(enum1)
like image 35
Sven Marnach Avatar answered Sep 21 '25 15:09

Sven Marnach