Wednesday 30 July 2014 — This is more than ten years old. Be careful.
One of the interesting things about helping beginning programmers is to see the way they think. After programming for so long, and using Python for so long, it’s hard to remember how confusing it can all be. Beginners can reacquaint us with the difficulties.
Python has a handy way to iterate over all the elements of a sequence, such as a list:
for x in seq:
doit(x)
But if you’ve only learned a few basic things, or are coming from a language like C or Javascript, you might do it like this:
i = 0
while i < len(seq):
x = seq[i]
doit(x)
i += 1
(BTW, I did a talk at the PyCon before last all about iteration in Python, including these sorts of comparisons of techniques: Loop Like a Native.)
Once you learn about the range() builtin function, you know you can loop over the indexes of the sequence like this:
for i in range(len(seq)):
x = seq[i]
doit(x)
These two styles of loop are commonly seen. But when I saw this on Stackoverflow, I did a double-take:
i = 0
while i in range(len(seq)):
x = seq[i]
doit(x)
i += 1
This is truly creative! It’s an amalgam of the two beginner loops we’ve already seen, and at first glance, looks like a syntax error.
In fact, this works in both Python 2 and Python 3. In Python 2, range() produces a list, and lists support the “in” operator for checking element membership. In Python 3, range() produces a range object which also supports “in”.
So each time around the loop, a new range is constructed, and it’s examined for the value of i. It works, although it’s baroque and performs poorly in Python 2, being O(n2) instead of O(n).
People are creative! Just when I thought there’s no other ways to loop over a list, a new technique arrives!
Comments
Are you sure about that? What python version? In my experimentations, the range is constructed just once.
But the for-statement syntax is "for VAR in EXPR:", and the while-statement syntax is "while EXPR:". The "in" keyword is part of the syntax of the for-statement, but part of the expression in the while-statement.
Add a comment: