|Ned Batchelder : Blog | Code | Text | Site|
» Home : Blog : July 2014
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:
(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:
These two styles of loop are commonly seen. But when I saw this on Stackoverflow, I did a double-take:
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!
tagged: python» 8 reactions