Let's say we have list with unknown number of indexes, is it possible to do something like
i=0
while foo[i]:
...
i+=1
In my example I get error because index will be out of range, but I think you got what I want?
what you are looking for is:
for i, elem in enumerate(foo):
#i will equal the index
#elem will be the element in foo at that index
#etc...
the enumerate
built-in takes some sequence (like a list, or a generator), and yields a tuple, the first element of which contains the iteration number, and the second element of which contains the value of the sequence for that iteration.
Since you specifically ask about an "unknown number of indexes", I also want to clarify by adding that enumerate
works lazily. Unlike len
, which needs to calculate/evaluate an entire sequence in advance (assuming that you are working with something more complicated than a simple list), and would thus fail for an infinite list, and take an indeterminate amount of time for some arbitrary generator function (which would then need to be run again, possibly leading to side effects), enumerate
only evaluates the next sequence in the list. This can be shown using the fact that it will perform as expected on the easiest to make example of a sequence with an unknown number of entries: an infinite list:
import itertools
for i, elem in enumerate(itertools.cycle('abc')):
#This will generate -
# i = 0, elem = 'a'
# i = 1, elem = 'b'
# i = 2, elem = 'c'
# i = 3, elem = 'a'
# and so on, without causing any problems.
EDIT - in response to your comments:
Using for ... enumerate ...
is inherently more expensive than just using for
(given that you have the overhead of doing an additional enumerate
). However, I would argue that if you are tracking the indexes of your sequence elements, that this tiny bit of overhead would be a small price to pay for the very pythonic presentation it affords (that is to say, i=0; i += 1
is a very C-style idiom).
After doing a little bit of searching, I dug up (and then agf corrected the url for) the source code for the enumerate function (and additionally, the reversed
function). It's pretty simple to follow, and it doesn't look very expensive at all.
if you have a python list, you can iterate through the list with a for loop:
for i in list
if you have to use the while loop, you can try
i=0
while i<len(foo):
...
i+=1
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