-2

I have a nested list comprehension, when I print the output, it gives me generator object, I was expecting a tuple.

vector  = [[1,2],[2,3],[3,4]]
res = (x for y in vector for x in y if x%2 == 0)
print(res)

I thought since I have small bracket for res assignment, I thought the result will be tuple, but it gives me a generator object.

But when I use a traditional approach, it gives me a list.

lst = []
for y in vector:
    print(y)
    for x in y:
        print(x)
        if x%2 == 0:
            lst.append(x)
print(lst)

It looks clear here that it gives a list there is no confusion here in the second one, but the first one is little confusing as why it gives a generator object.

Reactoo
  • 916
  • 2
  • 12
  • 40

1 Answers1

1

Python doesn't know that you want your generator expression to be a list until you make it one. ;^)

vector  = [[1,2],[2,3],[3,4]]
res = list((x for y in vector for x in y if x%2 == 0))  # use generator expression to make a list
print(res)

Output:

[2, 2, 4]
rhurwitz
  • 2,557
  • 2
  • 10
  • 18
  • 1
    Better don't encourage that, write a list comprehension instead. – Kelly Bundy Jan 22 '23 at 04:51
  • But how do we know which expression is creating a generator object? I am confused on that one. Is assigning a loop to a variable is enough for creating one?? – Reactoo Jan 22 '23 at 04:57
  • @Reactoo *"which expression is creating a generator object?"* - The generator expression. – Kelly Bundy Jan 22 '23 at 05:00
  • 1
    @Reactoo, it can be confusing, but there is a difference between a looping statement in Python and a generator expression although the syntax is similar. [Here is a good stackoverflow article](https://stackoverflow.com/questions/58256907/when-to-use-generator-functions-and-when-to-use-loops-in-python) on the differences. – rhurwitz Jan 22 '23 at 14:55