简体   繁体   中英

Trying to understand the following generator in python

I am trying to understand the difference between the following two code snippets. The second one just prints the generator but the first snippet expands it and iters the generator. Why does it happen? Is it because the two square brackets expand any iterable object?


#Code snippet 1


li=[[1,2,3],[4,5,6],[7,8,9]] 
for col in range(0,3):
    print( [row[col] for row in li] )`
Output: 
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

#Code snippet 2


li=[[1,2,3],[4,5,6],[7,8,9]]
for col in range(0,3):
    print( row[col] for row in li )

Output

<generator object <genexpr> at 0x7f1e0aef55c8>
<generator object <genexpr> at 0x7f1e0aef55c8>
<generator object <genexpr> at 0x7f1e0aef55c8>

Why is the output of above two quotes different?

The print function outputs the returning values of the __str__ method of the objects in its arguments. For lists, the __str__ method returns a nicely formatted string of comma-delimited item values enclosed in square brackets, but for generator objects, the __str__ method simply returns generic object information so to avoid altering the state of the generator.

By putting a generator expression in square brackets you're using list comprehension to explicitly make a list by iterating through the output of the generator expression. Since the items are already produced, the __str__ method of the list would have no problem returning their values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM