Mark Gritter (markgritter) wrote,
Mark Gritter
markgritter

Indexes and elements of Python sequences

A python for-loop can take any sequence as an argument, but sometimes you want both an index and the elements of a sequence. One way is to loop over the indices:

for i in xrange(len(sequence)):
  e = sequence[i]
  # do something with both i and e


The idiom I hadn't come up with on my own was:

for i, e in zip(range(len(sequence)),sequence):
  # do something with both i and e


PEP 212 calls this latter idiom "unintuitive" and suggests an addition to the language.

But, it seems to me that taking the length of the sequence is unnecessary, expensive, and not necessarily even well-defined. The built-in zip function terminates when the shorter sequence does, so we should be able to do:

for i, e in zip( itertools.count(), sequence ):
  # do something with both i and e


Or even better, use itertools.izip so that the result is generated entirely on-the-fly.
Tags: programming, python
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 5 comments