On Thu, Jun 29, 2017 at 2:57 PM, Irv Kalb <i...@furrypants.com> wrote: > Now I am looking at the change in the range function. I completely > understand the differences between, and the reasons for, how range works > differently in Python 2 vs Python 3. The problem that I've run into has to > do with how to explain what range does in Python 3. In Python 2, I easily > demonstrated the range function using a simple print statement: > > print range(0, 10) > > I discussed how range returns a list. I gave many examples of different > values being passed into range, and printing the resulting lists.
In Python 3 you could demonstrate this with: >>> print(list(range(0, 10))) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > Next, I introduced the concept of a for loop and show how you use it to > iterate over a list, for example: > > for number in [12, 93, -45.5, 90]: > # Some operation using each number (for example, adding up al the numbers) > > When that was clear, I would go on to explain how you could incorporate range > in a for loop: > > for someVariable in range(0, 10): > > explaining that range would return a list, and the for statement iterated > over that list. Very clear, very easy for new students to understand. You can still use the rest of this as is. range no longer returns a list directly but you can demonstrate its contents as a list above, and explain that the for statement iterates over the contents of the range. > But Python 3's version of the range function has been turned into a generator. It's not a generator, although that's a common misunderstanding since range is primarily used for iteration. It's still a sequence type; it just takes advantage of the regularity of its contents to store them efficiently by calculating them on demand rather than keeping them all in one big list. For example, you can still do all this: >>> rng = range(10) >>> print(rng) range(0, 10) >>> len(rng) 10 >>> rng[4] 4 >>> rng[3:5] range(3, 5) >>> rng.index(7) 7 >>> rng.count(4) 1 >>> print(list(reversed(rng[3:5]))) [4, 3] The biggest changes as far as usage goes are that its repr() no longer looks like a list, it's now immutable, and it can't be multiplied or added to other lists -- all of which are resolvable by first converting it to a list. So I don't think that you should really need to alter your approach much to teaching this. -- https://mail.python.org/mailman/listinfo/python-list