0

What is causing this error?:

int() argument must be a string, a bytes-like object or a number, not 'generator'

Context:

I'm trying to append the yield of a generator. Here is a minimal reproducible example:

def my_func(values, n):
    
    def my_gen():
        for x in values:
            yield x
    
    collections = []
    
    for i in range(0, n):
        collections.append(int(my_gen()))
        
    return collections
    
x = my_func([1, 2, 3, 4, 5], 2)
print(x)

Expected Output:

[1, 2]
thenarfer
  • 405
  • 2
  • 14
  • 3
    In `collections.append(my_gen())`, `my_gen()` means a new generator object, not the resulting yielded values. You need to collect those explicitly. The linked duplicate gives a good overview of how generators work generally. – Karl Knechtel Aug 05 '21 at 21:05
  • 1
    Your example isn't reproducible, I don't get that error. The code doesn't even mention int() – Alex Hall Aug 05 '21 at 21:10
  • You're right @AlexHall, I put the correct code snippet now. Thanks for the heads up! – thenarfer Aug 05 '21 at 21:13
  • 1
    What do you expect `int(my_gen())` to do? `int(values)` wouldn't work either for much the same reason, and my_gen() is semantically very close to `values`. Are you trying to convert *each element* of the list/generator to an int? – Alex Hall Aug 05 '21 at 21:15
  • The cause of the error is pretty explicit, you are passing a generator to `int` but the `int` constructor doesn't support generator objects. It is unclear what you thought that would do. – juanpa.arrivillaga Aug 05 '21 at 21:17
  • 1
    What is the point of `my_gen`? Or is this just a toy example? – juanpa.arrivillaga Aug 05 '21 at 21:17
  • The coding problem I'm trying to create my own solution for is this one: https://www.codewars.com/kata/59590976838112bfea0000fa/train/python – thenarfer Aug 05 '21 at 21:19
  • I was hoping that the generator would give me one element from the list at a time, so I later can add each element to the correct list in a loop. I am looking for one integer of the list `[1, 2, 3, 4, 5]` at a time. – thenarfer Aug 05 '21 at 21:22
  • 1
    `int(x)` is for converting `x` to an int, not retrieving an int from `x`. If you want `collections` to look like `[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]` then try replacing the append line with `collections.extend(my_gen())`. Or just replace the whole function with `return values * n`. If you want something else, explain what `my_func` is supposed to output. – Alex Hall Aug 05 '21 at 21:33
  • I realize that the output that I'm looking for is not to return the full generation [1, 2, 3, 4, 5] every time. When the for look runs (2 times), it should just get the next value of `values`. – thenarfer Aug 05 '21 at 22:04

0 Answers0