Python Generators Explained

2024 ж. 17 Мам.
141 646 Рет қаралды

Welcome back to another KZhead video! In this video, I will be talking about generators in Python. Generators are similar to iterators but a more advanced concept in the Python language. However, they are not too complicated and anyone should be able to follow along.
💻 Thanks to HiCounselor for sponsoring this video! Apply to their next cohort to land your dream job in tech here: hicounselor.com/ HiCounsoler not only provides great learning resources but also has great interview prep material!
⭐️ Timestamps ⭐️
00:00 | Overview
01:43 | Generators vs Iterators
02:40 | Iterators Explained
08:33 | next()
13:58 | iter()
15:24 | Creating Legacy Iterators
19:22 | Creating Generators
23:15 | Generators Use Case
26:58 | Generator Comprehensions
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
💰 Courses & Merch 💰
💻 The Fundamentals of Programming w/ Python: tech-with-tim.teachable.com/p...
👕 Merchandise: teespring.com/stores/tech-wit...
🔗 Social Medias 🔗
📸 Instagram: / tech_with_tim
📱 Twitter: / techwithtimm
⭐ Discord: / discord
📝 LinkedIn: / tim-ruscica-82631b179
🌎 Website: techwithtim.net
📂 GitHub: github.com/techwithtim
🔊 Podcast: anchor.fm/tech-with-tim
🎬 My KZhead Gear 🎬
🎥 Main Camera (EOS Canon 90D): amzn.to/3cY23y9
🎥 Secondary Camera (Panasonic Lumix G7): amzn.to/3fl2iEV
📹 Main Lens (EFS 24mm f/2.8): amzn.to/2Yuol5r
🕹 Tripod: amzn.to/3hpSprv
🎤 Main Microphone (Rode NT1): amzn.to/2HrZxXc
🎤 Secondary Microphone (Synco Wireless Lapel System): amzn.to/3e07Swl
🎤 Third Microphone (Rode NTG4+): amzn.to/3oi0v8Z
☀️ Lights: amzn.to/2ApeiXr
⌨ Keyboard (Daskeyboard 4Q): amzn.to/2YpN5vm
🖱 Mouse (Logitech MX Master): amzn.to/2HsmRDN
📸 Webcam (Logitech 1080p Pro): amzn.to/2B2IXcQ
📢 Speaker (Beats Pill): amzn.to/2XYc5ef
🎧 Headphones (Bose Quiet Comfort 35): amzn.to/2MWbl3e
🌞 Lamp (BenQ E-reading Lamp): amzn.to/3e0UCr8
🌞 Secondary Lamp (BenQ Screenbar Plus): amzn.to/30Dtafi
💻 Monitor (BenQ EX2780Q): amzn.to/2HsmUPZ
💻 Monitor (LG Ultrawide 34WN750): amzn.to/3dSD7tS
🎙 Mic Boom Arm (Rode PSA 1): amzn.to/30EZw9m
🎚 Audio Interface (Focusrite Scarlet 4i4): amzn.to/2TjXsih
💸 Donations 💸
💵 One-Time Donations: www.paypal.com/donate?hosted_...
💰 Patreon: / techwithtim
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
⭐️ Tags ⭐️
- Tech With Tim
- Generators
- Generators Explained
- Iterators
- Python
- HiCounselor
⭐️ Hashtags ⭐️
#TechWithTim #Generators1

Пікірлер
  • I started programming 60 years ago. Thank you Tim for teaching an old dog new tricks.

    @goboy6882@goboy68822 жыл бұрын
    • wow, life long learning!!!

      @Ian-bb7vv@Ian-bb7vv2 жыл бұрын
    • Wow

      @piadas804@piadas8042 жыл бұрын
    • What was it you were learning 60 years ago? Was it COBOL? Fortran? I started programming in 1980/81 but it was BASIC by then, and I graduated to COBOL and Fortran, eventually settled on C++ as my go-to language.

      @JasonJorgensonPhD@JasonJorgensonPhD2 жыл бұрын
    • Lies!🥱🥱🥱

      @me-zu3gm@me-zu3gm Жыл бұрын
    • ​@@me-zu3gm how u know😂

      @thelavagod@thelavagod Жыл бұрын
  • I very rarely leave comments on tutorials, but this was so incredibly well and robustly explained that I seriously need to leave my comment of appreciation, it was so clear to understand!

    @williamselinder9138@williamselinder91384 ай бұрын
  • Thanks Tim. You have become the go-to guy when I learn stuff and get stuck. your explanations are very practical. as a new programmer who's attempting to beef up my resume, I have been teaching myself python. you have been a great resource, keep it up. THANK YOU!

    @gustavocinci4044@gustavocinci40442 жыл бұрын
  • It is nice and refreshing to see a presentation of the back-end logic to the magic functions we have in Python. As much as I love the built-in functions - I really love knowing how they do what they do.

    @Factory400@Factory4002 жыл бұрын
  • i watched this video just to learn something new about python, turns out the generator is really applicable in my code and has helped memory usage heaps. Thanks!

    @vinni113@vinni1132 жыл бұрын
  • This channel is just so incredible! i can't tell how much i learned from this channel, thank you

    @AleVZero@AleVZero2 жыл бұрын
  • Great video and explanation! Was going to look for “how to process large amounts of data”, but clicked on this instead. Turned out to be the core of the answer👍

    @tyrelllaszlo6024@tyrelllaszlo60242 жыл бұрын
  • Good thing about this video is that it walks you through other concepts too such as class and dunder methods which is kind of a good refresher to what I have studied earlier. You've earned a subscriber Tim!

    @NabeelButt@NabeelButt2 жыл бұрын
  • good stuff Tim, there's never enough of knowledge about python

    @michapodlaszuk9025@michapodlaszuk90252 жыл бұрын
  • Great video! Best explanation I’ve seen so far on this topic!

    @fredericoamigo@fredericoamigo2 жыл бұрын
  • could have added example of "yield from" as well. A great coding exercise would be, print inorder traversal of binary tree using generators.

    @harshraj22_@harshraj22_2 жыл бұрын
    • Great idea!

      @TechWithTim@TechWithTim2 жыл бұрын
    • ok please explain what "inorder traversal of binary tree" is

      @xx-jk1iq@xx-jk1iq2 жыл бұрын
    • @@xx-jk1iq Traversing a tree is just the order in which you access it's nodes. In-order traversal of a binary tree means you visit the left branch, then the current node, and then the right branch. Basically put it visits the nodes in ascending order.

      @gregfrost8399@gregfrost83992 жыл бұрын
    • @@gregfrost8399 but from what I thought, a binary tree isn't a linear sequence. So how would that work

      @xx-jk1iq@xx-jk1iq2 жыл бұрын
    • @@xx-jk1iq Say we have the following tree: A / \ B C / \ D E In order traversal does the following: 1. searches the left branch until it finds a leaf node 2. visits (e.g. prints) the current node 3. searches the right branch until it finds a leaf node Once it has completed the 3 steps it will return upwards to it's parent node The result = (D, B, E, A, C)

      @gregfrost8399@gregfrost83992 жыл бұрын
  • Wow! This was so refreshing and highly insightful. Thanks so much Tim for this really helpful video on generators. It helped me a lot understand this better!

    @TheRealKitWalker@TheRealKitWalker Жыл бұрын
  • Thanks you. This was really interesting. It's crazy how the most someone knows about how something works, then for intuition you can understand other stuff or libraries created from others. One of the usefully methods I use as a fast document of a library is "dir"

    @LNMLucasMasiero@LNMLucasMasiero2 жыл бұрын
  • I appreciate the video, Tim! I have a much better understanding of Python generators now.

    @ChromaDotNova@ChromaDotNova2 жыл бұрын
  • Really appreciate your videos. Thank's for sharing your knowledge. I'm just at the start with Python deep-diving, but already it keeps getting me staying awake at night. So many possibilities :D Keep on the good work

    @STFU665@STFU665 Жыл бұрын
  • I would love to see a video on how you record and edit your videos Man This is some real good quality content!!

    @saishyam8583@saishyam85832 жыл бұрын
    • Indeed it is, I've learned a ton of stuff from him about Python.

      @Mr_Spock512@Mr_Spock5122 жыл бұрын
  • This video provides a clear image of how it works. Thank you.

    @MissingTricks@MissingTricks Жыл бұрын
  • Amazing explanation! Learn a lot from it. Thank you soo much!!

    @ddbarenco@ddbarenco2 жыл бұрын
  • This was an awesome video Tim. I'm learning about Deep Learning and generators have been particularly useful for chunking up huge datasets for feature extraction as it would be impossible to read them all into memory on my laptop. Now I understand how and why this works as a Python newbie. The explanation on Iterators was great too. I love the nuts-and-bolts detail on what’s going on under the hood. Many thanks.

    @CaratacusAD@CaratacusAD Жыл бұрын
  • i love your videos man, and your clarity of explanations, carry on!

    @anirbanc88@anirbanc882 жыл бұрын
  • Love your vids! Great as always!

    @abdullahmohammed6115@abdullahmohammed61152 жыл бұрын
  • This video has so much value! Thank you

    @gustavojuantorena@gustavojuantorena2 жыл бұрын
  • You're a great teacher, congrats!

    @rodrigo2112-@rodrigo2112- Жыл бұрын
  • Now i can finally understand generators! Thanks Tim!!

    @network_noob@network_noob2 жыл бұрын
  • Hi Tim, you keep providing us useful contents: I'm glad for everything you've been doing! I'm truly interested in CS, and curious about how much of these information you have learned at university or on your own. Could you please answer me?

    @enzovalendino606@enzovalendino6062 жыл бұрын
  • the example for the generator is perfect , thanks!!!

    @omarelsebaey9589@omarelsebaey95892 жыл бұрын
  • For a deeper dive into generators, you can go into how you can use .send to update process parameters that may not have been relevant when initially creating the object. This was an area that originally stumped me when I was looking at some more advanced examples of generators as the function took in one set of parameters, but the subsequent calls with yield accepted different parameters. A very neat trick and one of the reasons why I find myself growing more enamored with the language.

    @bipolarchemist@bipolarchemist2 жыл бұрын
    • One can update objects at any time with a call to an object method just like one can update the value in a loop variable with a simple assignment. Writing a loop and an assignment makes the code readable for absolutely everybody with even the slightest amount of knowledge about procedural programming languages. Using send() will make 99% of programmers scratch their heads (including the ones who know what it does) and ask what kind of idiot will use such a construct. Guess who they mean by "idiot". They mean you. And that, by the way, includes yourself. You will call yourself an idiot for using this construct the first time you have to read your own code six months later. Simple is beautiful. Keep it simple.

      @lepidoptera9337@lepidoptera9337 Жыл бұрын
  • It really is a great video. Thank you!!!!. One of the best generators video generated🙂.

    @manishsingh900@manishsingh9002 жыл бұрын
  • Great stuff mate,thank you and cheers!

    @vammy55@vammy552 жыл бұрын
  • I learned new things which don't know anything about that. Thanks to make such a nice video for us. ☺️☺️👏👏

    @onlyforscience8255@onlyforscience82552 жыл бұрын
  • Tons thanks, only video which clearly said what is iterator and generator - CRYSTAL CLEAR.

    @parvishrao6414@parvishrao64142 жыл бұрын
  • Great job breaking it down 👍🏼

    @NearLWatson@NearLWatson Жыл бұрын
  • Useful tutorial for me. Thanks.

    @eddywang5035@eddywang50352 жыл бұрын
  • Thanks Tim. One question. So creating generator don't even take up disk space? Say I have a for-loop that downloads a file, yield data, then delete the file where end result is a generator. This won't take up disk space and only memory upon calling __next__()?

    @haneulkim4902@haneulkim49029 ай бұрын
  • ******BEST GENERATOR EXPLAINATION********** read 3 books + 4 online tutorials, still confused about Generators******* Finally, got it ............!!!! Awesome Brother !!!!!

    @ChandanSingh-bh7wu@ChandanSingh-bh7wu2 жыл бұрын
  • Amazing video Tim. Thank you

    @davidring5071@davidring5071Ай бұрын
  • awesome content, keep up with these videos Tim

    @Barejs@Barejs2 жыл бұрын
  • Thanks for the video, well explained

    @amalkrishnas1696@amalkrishnas1696 Жыл бұрын
  • Excellent Video, thanks!

    @estebangarro7254@estebangarro7254 Жыл бұрын
  • Great video. You have a good format. Don't change it =)

    @Mdroudian@Mdroudian2 жыл бұрын
  • Wow, really well explained, good that stumbled upon this. If u can do the same with other python(decorators...) and c++ concepts like this, pls. Subbed and liked,

    @elitearmedforce@elitearmedforce2 жыл бұрын
  • Looking forward to "Learning Cobol with Tim" course !

    @johnnytoobad7785@johnnytoobad77852 жыл бұрын
  • thats brilliant video!

    @boooringlearning@boooringlearning2 жыл бұрын
  • You can use ctrl + d to copy a line to the next line without copy pasting in pycharm, not sure if something like that in sublime.

    @danielmarx3106@danielmarx31062 жыл бұрын
  • lets goo new tech with tim

    @aryankathawale9269@aryankathawale92692 жыл бұрын
  • Thanks!

    @servantofourlordjesuschris6456@servantofourlordjesuschris64569 ай бұрын
  • Thank you !!

    @JaBoss397@JaBoss397 Жыл бұрын
  • Could you make a video about Web scraping by using requests and beautifulsoup modules?And maybe some decorators would be great : )

    @berkaybb5733@berkaybb57332 жыл бұрын
  • Thank you!

    @alexandruteodor3585@alexandruteodor35856 ай бұрын
  • Thanks for the good stuff

    @yoyokoko5153@yoyokoko51532 жыл бұрын
  • @14:40, if I would print(next(iter(x))) it would give me 1 thats true, but if I would do that again, I would get another 1 and so on. So it does not go to the next Element. That was kind of confusing to me. So I guess, you have to make the variable "x" an iter first, and then you can use the next(x) function to "jump" to the next element. Or did I not understand that right?

    @Kema109@Kema1099 ай бұрын
  • First time i understood what you are saying....☺

    @bradyb2415@bradyb24159 ай бұрын
  • How does a for loop work on an object that is already an iterator, like map() function you showed? Does Python implicitly know if the .__iter__() method needs to be called, or if it doesn't?

    @grantpeterson2524@grantpeterson2524 Жыл бұрын
  • 09:46 and on: Hi I'm a total noob and I don't get why for loop is able to pick the iteration up from where the last next call left it. why does the for loop know what happens before it? Is where next stops also stored and the loop preprogrammed to check that address? I'm sorry if I've misused words, I just don't know how else to ask about it. Any tip would be much appreciated. Also thanks to the maker of this video.

    @korkunctheterrible4302@korkunctheterrible43022 жыл бұрын
  • thank you, Tim

    @thaimeuu@thaimeuu4 ай бұрын
  • Love your Vids Tim! keep up the good work(hope u heart this!)

    @rekhasurya3536@rekhasurya35362 жыл бұрын
  • This is a super tutorial! Super helpful and clear explanation! Tim, you are awesome! Thank you so much!!!

    @barbaraulitsky8292@barbaraulitsky82922 жыл бұрын
  • Thank you genius!

    @Tussu17@Tussu172 жыл бұрын
  • Damn I love this channel

    @alexramirez5104@alexramirez51042 жыл бұрын
  • You should put the 'Pause 1' before the 'yield 1', I suspect, otherwise the pause text appears on the next call, not the one it refers to. Just learning Python - this is great.

    @antmitchell9930@antmitchell99302 жыл бұрын
    • yeah, he should've done that so everyone can know when is the 'Pause 1' getting printed

      @whatdoiputhere5089@whatdoiputhere50892 жыл бұрын
    • but the execution pauses after the yield, so pause 1 before makes no sense.

      @user-zb8tq5pr4x@user-zb8tq5pr4x2 жыл бұрын
  • Awesome 🎉

    @UgochukwuEzeani-ut6vd@UgochukwuEzeani-ut6vd4 ай бұрын
  • I like how the first generator example is literally obscolete because you used for i in range: to say for i in range:

    @robinferizi9073@robinferizi90732 жыл бұрын
  • what is that code editor tim using ?plzzzzzzz

    @mohamedelzend2337@mohamedelzend23372 жыл бұрын
  • we, we had teachers who didn't know these stuff😂😂😂, and graduated without this knowledge😊😊😊

    @innocentharelimana4449@innocentharelimana4449Ай бұрын
  • Please make a pygame video explaining sprites

    @georgianabhishek3561@georgianabhishek35612 жыл бұрын
  • It’s better to say next() consumes the list. If you printed the list y after invoking next() four times the console showed you the iterated elements don’t exist anymore in y.

    @mufasaruleroftheanimalking1026@mufasaruleroftheanimalking102612 күн бұрын
  • Hi Tim can you explain interface in python?

    @lukaszno8988@lukaszno89882 жыл бұрын
  • super good

    @robinbreed2439@robinbreed2439 Жыл бұрын
  • when i put the code at 7:29 into IDLE, (for i in y: print(i)), nothing happened. You got the list output. Why is that?

    @mgmartin51@mgmartin512 жыл бұрын
  • If for loop stops by the exception, it's not clear where gen() raise the exception. Or there is a different logic inside for() .

    @jphvnet@jphvnet Жыл бұрын
  • Could you make a video on C extensions for Python? It took a while for me to learn as there aren't many resoruces out there and the documentation is partially outdated, but the speed increase using such extensions is exponential with regards to input size. I think a tutorial on this topic would prove highly useful to newcomers. I've already written an article about them on Medium, but I think you, Tim, can do a much better job at explaining them.

    @nicholas_obert@nicholas_obert2 жыл бұрын
    • Yes, this would be nice. Does Tim know C though? If so, I've love to learn how to integrate C and Python

      @hossumquat@hossumquat2 жыл бұрын
    • @@hossumquat he has made a series about C++, plus C is very easy at a beginner level.

      @nicholas_obert@nicholas_obert2 жыл бұрын
    • @@nicholas_obert Ah, ok, didn't know that. I'd guess he already knows this then and could teach it. Awesome!

      @hossumquat@hossumquat2 жыл бұрын
  • hi i wonder any python seniors could answer my question , i just started learning python and the things i learned included all the basics (i assumed) (exp:file handling,oop,the basic commands,if,loop,tuple,dict.....).Besides,i also learned some algorithms like linked list,binary tree,stack&push.For now ,what should i do in the next step?

    @wubangzheng@wubangzheng2 жыл бұрын
    • i did some python projects as well like creating a simple alien invasion game

      @wubangzheng@wubangzheng2 жыл бұрын
    • I'm not a senior, but I think working on projects is the best way. Do webscraping with selenium, API calls with requests, build a small website with django, use pandas to work with relational data, then improve all of the IO bound tasks with asyncio

      @Plepple@Plepple2 жыл бұрын
  • Awesome

    @UgochukwuEzeani-ut6vd@UgochukwuEzeani-ut6vd4 ай бұрын
  • Hiyo tim! Good tutorial as always! Could you think about making more c++ content, and teach us about c++ libraries?

    @elpython3471@elpython34712 жыл бұрын
  • Thanks genius :)

    @amrsalaheldinabdallahhammo663@amrsalaheldinabdallahhammo663 Жыл бұрын
  • What text editor are you using?

    @64imma@64imma Жыл бұрын
    • sublime text

      @entity5678@entity5678 Жыл бұрын
  • Tim what can I do with a computer science degree except programming!? 👍👉💪

    @terryr5713@terryr57132 жыл бұрын
  • Could anyone help me of how to show the [Finished in X ms] in the console?

    @pabloshi4863@pabloshi48632 жыл бұрын
  • How your code showing the run time..?

    @neerajvaradi8505@neerajvaradi85052 жыл бұрын
  • Can you create a "screen recorder"app on python please

    @tcgvsocg1458@tcgvsocg14582 жыл бұрын
  • what's that font (name?)

    @HarryBGamer2570@HarryBGamer2570 Жыл бұрын
  • can you do a video about testing Tim, i heard spaceX is using Python for testing

    @youssefelamrani7905@youssefelamrani79052 жыл бұрын
    • what do you mean by testing?

      @xx-jk1iq@xx-jk1iq2 жыл бұрын
  • the object returned by open("foo.txt", "r") has an iterator that walks through the file a line at a time.

    @ncmathsadist@ncmathsadist Жыл бұрын
    • That's too easy for the man. He needs to make things complicated. ;-)

      @lepidoptera9337@lepidoptera9337 Жыл бұрын
  • After every explanation: “HOPEFULLY that KINDA makes sense”. Yes bro it makes sense ffs.

    @Jschmuck8987@Jschmuck89872 ай бұрын
  • Nice

    @belowasmelashgebremariam@belowasmelashgebremariam Жыл бұрын
    • Asme Tchaikovsky climb to uucp

      @belowasmelashgebremariam@belowasmelashgebremariam Жыл бұрын
    • Razed St Ed Sry egg re zed zarathustra ink

      @belowasmelashgebremariam@belowasmelashgebremariam Жыл бұрын
  • Hi Tim

    @Aidanbaro@Aidanbaro27 күн бұрын
  • Thanks for the explanation. Btw, are you interested in making a video about Cython ( C amd C++ extension on Python ) ? Thank you in advance!

    @SkyFly19853@SkyFly198532 жыл бұрын
    • Yep. I have tried using cython, but encountered IDE errors and performence issues.

      @jonathan3488@jonathan34882 жыл бұрын
    • @@jonathan3488 I see... Even so, I think it has the potential.

      @SkyFly19853@SkyFly198532 жыл бұрын
  • good

    @ilyasseidkhebbach3812@ilyasseidkhebbach3812 Жыл бұрын
  • Хвала!

    @stele339@stele339 Жыл бұрын
  • Why would we want to implement our won iterators? Edit: So, we don't need to create iterators, because they have been replaced with generators?

    @laponiec@laponiec10 ай бұрын
  • tim finally decided to change from monokai

    @shawnbeans7389@shawnbeans73892 жыл бұрын
  • Tell me your theme and color of vs code pleaseeee🥺

    @avigupta6064@avigupta60642 жыл бұрын
    • He’s not using vs

      @error2839@error28392 жыл бұрын
    • @error i know, i am just talking in general like that spotify api tutorial he did.

      @avigupta6064@avigupta60642 жыл бұрын
  • This guy is almost like Mark Z.

    @malanbandara@malanbandara2 жыл бұрын
  • Ahh, you also forgot the send method of the generator. That might be it's own video tho as it's the base of coroutine

    @memk@memk2 жыл бұрын
  • here before 8 comments

    @aryankathawale9269@aryankathawale92692 жыл бұрын
  • I think your comparison between the generator and "legacy" syntax is a bit unclear. The class based iterator seems way more inconvenient than it acutally is since you used "range" in the generator but implemented a range-like behavior from scratch in your class. When returning a range object in the _ _ iter _ _ method the class would not be that more bloated and actually useful depending on your use case. I think it could've been made more clear that a generator relies on existing iterators while the iterator class, well, does not since it is made to provide its own iterator.

    @comedyclub333@comedyclub3332 жыл бұрын
    • generators need not rely on existing iterators... def upto(x): current = 0 while current

      @gagansai8880@gagansai88802 жыл бұрын
    • @@gagansai8880 Yeah, you are right. Totally forgot about the fact that for loops and while loops are interchangable. I wrote bullshit about generators relying on existing iterators. My criticism still remains that the way custom iterator classes and generators are compared is not really fair.

      @comedyclub333@comedyclub3332 жыл бұрын
    • @@comedyclub333 I don't understand. Wasn't it said or implied in the vid somewhere that yield uses next() as a built in? (I am not a geek or anything, I truly don't understand and I am a 5 year old when it comes to this)

      @korkunctheterrible4302@korkunctheterrible43022 жыл бұрын
  • Those 2 thumbs-downers had their computers upside down.

    @jammincoder@jammincoder2 жыл бұрын
  • When u say hopefully that is clear, and i think nope, i stlll dont get it...

    @wongkingshun@wongkingshun Жыл бұрын
  • The range function is actually xrange. Xrange was renamed to range and the old range function is gone. The xrange function stores the result in a xrange object, not an array, which is why the new range function is smaller than the old one. Also, you can just use “for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]”

    @abcdxcxd8280@abcdxcxd82802 жыл бұрын
  • I like his videos but the range does not really return an iterator!

    @adarshsurendran4347@adarshsurendran434711 ай бұрын
KZhead