YSA
YSA

Reputation: 879

Why does this Python code return a generator object?

Here's the part of the code that confuses me (explained below):

class Node:
    def __init__(self, start, end):
        self.start = start
        self.end = end

intervals = [Node(1, 2), Node(3, 4), Node(5, 6)]

starts = sorted(i.start for i in intervals)
ends = sorted(i.end for i in intervals)

Why does (i.start for i in intervals) return a generator object and why does removing the parentheses like so i.start for i in intervals returns an invalid syntax error?

Upvotes: 0

Views: 130

Answers (1)

ChristianFigueroa
ChristianFigueroa

Reputation: 804

(x for x in y) is a shorthand way to create a Python generator. If you want to iterate through the list, use

for x in y:
    # do stuff

The parentheses let Python parse the expression as one token, which lets it know you are trying to create a generator. Without the parentheses, Python initially sees the i.start, so it's expecting an expression. The for keyword throws it off though since that start a new statement. The parentheses group it all together into one token when the interpreter reads it, so Python is able to recognize it as the generator syntax.

Upvotes: 2

Related Questions