Learnerer
Learnerer

Reputation: 583

Lambda as iterator in Python returns function object on first iteration

I have this code snippet which I can't understand:

>>> l = lambda: -4, 'c', 0
>>> i = iter(l)
>>> i
<tuple_iterator object at 0x00700CD0>
>>> next(i)
<function <lambda> at 0x0070A4F8>
>>> next(i)
'c'
>>> next(i)
0
>>> next(i)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>>

Why is it returning lambda object on first iteration, instead of -4?

Upvotes: 3

Views: 1313

Answers (2)

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6935

When you do this :

>>> l = lambda: -4, 'c', 0

l is actually a tuple containing first item as a lambda function, second item a string and third item an integer.

It is equivalent to the following :

>>> l = (lambda: -4, 'c', 0)

If you want to get access to the lambda function which returns -4, you should try this :

>>> i = iter(l)
>>> next(i)()
-4

But note that next(i)() works only with callable(lambda, functions etc) objects. If you use next(i)() with a string object python will raise TypeError: 'str' object is not callable. So always check if the item is callable. ie,

i = iter(l)
item = next(i)
if callable(item):
    print(item())
else:
    print(item)

Upvotes: 6

Sweeper
Sweeper

Reputation: 273188

I think you might have misunderstood what l is.

l is a tuple of 3 elements:

  • a lambda that returns -4
  • the string c
  • the integer 0

When you create an iterator iterating through the tuple, of course the first call to next is going to give you a lambda!

Maybe you meant to call the lambda:

next(i)()

Or maybe you meant to declare l like this:

l = lambda: (-4, 'c', 0) # you might think you don't need the parentheses, but you do

A lambda that returns a tuple.

And then do iter(l()).

Upvotes: 6

Related Questions