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
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...
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With