Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
problem in using enumerate
#3
The first for loop uses up all the values in the iterable "e". There is nothing left to use. If you try to get another item, a StopIteration exception is raised.
e = enumerate("abcd")
for index, letter in e:
    print(index, letter)
next(e)
Output:
0 a 1 b 2 c 3 d Traceback (most recent call last): File "...", line 4, in <module> next(e) StopIteration
A for loop does the next(iterable) and try/except StopIteration for you. Kind of like this:
e = enumerate("abcd")
while True:
    try:
        index, letter = next(e)
        print(index, letter)
    except StopIteration:
        break
akbarza likes this post
Reply


Messages In This Thread
problem in using enumerate - by akbarza - Oct-09-2023, 01:12 PM
RE: problem in using enumerate - by perfringo - Oct-09-2023, 03:36 PM
RE: problem in using enumerate - by akbarza - Oct-11-2023, 09:52 AM
RE: problem in using enumerate - by perfringo - Oct-11-2023, 10:55 AM
RE: problem in using enumerate - by deanhystad - Oct-09-2023, 03:46 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  The use of enumerate Frankduc 3 1,754 Jan-31-2022, 09:40 PM
Last Post: deanhystad
  Need to understand the way enumerate() function works abhishekambastha 2 2,524 Sep-16-2018, 08:21 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020