What is a progression (range)?

when x = range(10), x stores a generator range(10).

I wonder then does ‘x’ have all the numbers between 0~9?
This concept quite eludes me because a generator is an ‘action’ that produces a number one by one, then when storing it into a variable and returning it produces what? My question originates from the code below.

def csv_reader(file_name):
    file = open(file_name)
    result = file.read().split("\n")
    return result

My first understanding of the code was, since ‘open()’ is a generator that yields line by line, ‘result’ would have simply the ‘first line’ of the whole text. But it seems result stores the ‘whole’ file and runs into ‘MemoryError’.

Also, as for the code below,

def csv_reader(file_name):
    for row in open(file_name, "r"):
    yield row

‘open()’ is a generator that has a ‘yield’ statement, and there is also a ‘yield’ statement in the function. Then does the function end up having a double ‘yield’ statement?

I just found out a curious thing about range. It is not an ‘iterator’?

1 Like

In essence, yes. range() is an iterable that knows where to start, and according to the step what is the next value in the range, and it knows where to stop.

>>> x = range(10)
>>> list(x)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Not sure that is the case. The for loop containing a yield is the generator, if I’m not mistaken.

1 Like

If we’re talking Python3 Range is a bit of a special case in that it creates a range object whereas it used to create a list in Python2. Now it returns an iterable range object (an immutable, low memory sequence-like object). It’s not an iterator, it can’t be exhausted and it supports certain actions common to sequences like slicing and containment testing but not others. The docs have some nice examples-

As for open() it returns a file object, not a generator. I think it might be worth spending a little time getting to know the relevant terms in Python or it could get quite confusing. Not every iterable is an iterator, not every iterator is a generator.
Glossary docs-
Perhaps a nicer link to look through to work out the differences but there are plenty of similar topics with a quick search-