🤔 Python generators

What are they? How to use them?

#Python

🧵Let's find out 👇

1️⃣ Python generators are lazy iterators delivering the next value when their .next() is called.

They are created by using the yield keyword

next() can be called explicitly or implicitly inside for loop

They can be finite or infinite
2️⃣ yield - where a value is sent back to the caller, but the function doesn’t exit afterward as with the return statement

The state of function is remembered.

For example, the number is incremented and sent back from yield at the consecutive call next()
3️⃣ Generator stores only the current state of the function - it generates next element on next() call and forgets the previous one -> it saves memory

For example, we don't need to store 1mio elements in memory to do something with each element
4️⃣ When you call a generator function generator object is returned - it's not executed yet

It executes only when next() is called

For example, that's why Exception is raised only on the next() call
5️⃣ When the generator goes out of elements it raises StopIteration exception
6️⃣ You can also create a class that behaves like a generator - it needs implemented methods:

- __iter__ -> to enable iteration
- __next__ -> to enable next element access
7️⃣ You can also create a generator with one-liner expression similar to list comprehension
8️⃣ You can read more:

https://t.co/mXp7L8l2Ai

More from Machine learning

10 machine learning YouTube videos.

On libraries, algorithms, and tools.

(If you want to start with machine learning, having a comprehensive set of hands-on tutorials you can always refer to is fundamental.)

🧵👇

1⃣ Notebooks are a fantastic way to code, experiment, and communicate your results.

Take a look at @CoreyMSchafer's fantastic 30-minute tutorial on Jupyter Notebooks.

https://t.co/HqE9yt8TkB


2⃣ The Pandas library is the gold-standard to manipulate structured data.

Check out @joejamesusa's "Pandas Tutorial. Intro to DataFrames."

https://t.co/aOLh0dcGF5


3⃣ Data visualization is key for anyone practicing machine learning.

Check out @blondiebytes's "Learn Matplotlib in 6 minutes" tutorial.

https://t.co/QxjsODI1HB


4⃣ Another trendy data visualization library is Seaborn.

@NewThinkTank put together "Seaborn Tutorial 2020," which I highly recommend.

https://t.co/eAU5NBucbm

You May Also Like

I think a plausible explanation is that whatever Corbyn says or does, his critics will denounce - no matter how much hypocrisy it necessitates.


Corbyn opposes the exploitation of foreign sweatshop-workers - Labour MPs complain he's like Nigel

He speaks up in defence of migrants - Labour MPs whinge that he's not listening to the public's very real concerns about immigration:

He's wrong to prioritise Labour Party members over the public:

He's wrong to prioritise the public over Labour Party