Rodrigo ๐Ÿ๐Ÿš€
Rodrigo ๐Ÿ๐Ÿš€

@mathsppblog

8 Tweets 5 reads Mar 28, 2023
Generators are a really cool Python ๐Ÿย tool.
Let me show you why you should bother learning them! ๐Ÿš€
A short thread: ๐Ÿ‘‡
I have a CSV file that lists all โ€œpurchasesโ€ of my free book โ€œPydon'tsโ€.
I want to go over that data to find the people who paid money for the book.
Then, I want to do something with that data.
I could write the code below ๐Ÿ‘‡
But what's an issue with it?
I'm loading ALL the data into memory and there really is no point in doing that.
I can filter out free downloads while going over the file the first time.
Something like you can see below ๐Ÿ‘‡
Butโ€ฆ what's an issue with this approach?!
The issue is that I look at this data often, and I only need the more recent paid sales.
When I find an โ€œoldโ€ sale, I just exit the script.
So, I am loading ALL paid sales for nothing!
Using a generator lets me retrieve paid sales, one at a time! ๐Ÿš€
But, why bother?
Generators are awesome ๐Ÿ”ฅ for two reasons:
๐Ÿ‘‰ย save memory: because you don't have to hold everything in memory all at once; and
๐Ÿ‘‰ย save time: because you don't need to compute everything upfront if you are exiting early.
So, want to learn about generators?
I'm writing about them in the Mathspp Insider ๐Ÿ๐Ÿš€ย newsletter.
This thread was about last week.
Tomorrow, I'm sending another issue about generators and how to handle them in your code.
You can read last week's issue (about generators) & subscribe here: insider.mathspp.com
So, to wrap up,
๐Ÿ‘‰ย generators let you handle data bit by bit, instead of doing everything all at once;
ย ๐Ÿ‘‰ย you use `yield` to send an item at a time;
ย ๐Ÿ‘‰ย you may save a lot of memory/time by using generators.
And finally:
If you got something out of this thread:
๐Ÿ‘‰ย follow me @mathsppblog for more Python ๐Ÿย knowledge; and
๐Ÿ‘‰ย retweet the tweet below to share this thread with your audience!
That's it for now! ๐Ÿš€
I'll see you around. ๐Ÿ‘‹

Loading suggestions...