264.6 DE - Writing to csv (Unable to understand Generator object to list object)

In the function below, the function parse_log(log) returns a generator object.
I am unable to understand, how passing a generator object as an argument returns an iterable list.

here lines is actually a “parsed”(generator object) then how a list comprehension works on it.

lines = [header] + [l for l in lines]

Does the instance “parsed” of the function parse_log(log) takes line by line from the log file and process it, cleans it and then we can take and write it to csv.

import csv

log = open('example_log.txt')
parsed = parse_log(log)

def build_csv(lines,header=None,file=None):
    if header:
           lines = [header] + [l for l in lines]
    writer = csv.writer(file,delimiter=',')
    print(type(writer))
    print(type(file))
    writer.writerows(lines)
    print(file.seek(0))
    file.seek(0)
    return file

Some objects are allowed as the second token in a for statement:

for each_var in obj:
    pass

These objects — i.e. the ones that can take the place of obj above are called iterables. A few iterables you’ve encountered thus far are strings, lists and tuples:

>>> for x in "dq": print(x)
d
q
>>> for x in ["d", "q"]: print(x)
d
q
>>> for x in ("d", "q"): print(x)
d
q

Any of these objects can be used inside a list comprehension even if they aren’t lists:

>>> print([x for x in "dq"])
['d', 'q']
>>> print([x for x in ("d", "q")])
['d', 'q']

This is simply a feature of list comprehensions, anything that can be used with a for loop can also be used in a list comprehension. You also have set and dictionary comprehensions, and they share this feature.

It just so happens that generators are iterables as well. This implies that you can use them as the second token in a for loop, and consequently that you can also use them inside comprehensions.

As a bonus, you can also have generator comprehensions:

>>> gen = (x for x in "dq")
>>> type(gen)
<class 'generator'>

And to confirm what was mentioned above, let’s use gen to create a list using list comprehension:

>>> print([x for x in gen])
['d', 'q']

I hope this helps.