Lazy evaluation in python with simple example

Things become interesting and even the harder concept becomes easier when we have a simple example to showcase the idea. Today I am trying to put the idea of lazy evaluation with a very simple python codes, using a single built in function.

lazy evaluation in python with example

To test the process we need to run the application in python2 and python3

numbers = range(1,10000000000000)
for item in numbers:
    print item

Run it in python-2 and we will run into memory issue. Particularly, will say memory overflow. Which means it tried to put all the numbers in the range in the memory and could not do it.

Solution is lazy evaluation. To get the values only when required. So try running the same line of code and it will run smoothly without any memory issue. So what had exactly happened is. It didn’t put all the values in range into memory and our for loop fetched the value that is required and displayed it.

I hope, I have tried my best to make the concept clear. So try to make your function lazy evaluated as possible when it comes to handling large data.

Leave a Reply