Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing loop while list has indexes in python

Tags:

python

list

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?

like image 231
Templar Avatar asked Nov 28 '22 18:11

Templar


2 Answers

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.

like image 166
Nate Avatar answered Dec 06 '22 18:12

Nate


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
like image 25
Will Avatar answered Dec 06 '22 19:12

Will