Python Generators Explained

Sdílet
Vložit
  • čas přidán 5. 06. 2024
  • Welcome back to another CZcams 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 CZcams 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

Komentáře • 172

  • @goboy6882
    @goboy6882 Před 2 lety +108

    I started programming 60 years ago. Thank you Tim for teaching an old dog new tricks.

    • @Ian-bb7vv
      @Ian-bb7vv Před 2 lety +7

      wow, life long learning!!!

    • @piadas804
      @piadas804 Před 2 lety +2

      Wow

    • @JasonJorgensonPhD
      @JasonJorgensonPhD Před 2 lety +6

      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.

    • @me-zu3gm
      @me-zu3gm Před rokem +1

      Lies!🥱🥱🥱

    • @thelavagod
      @thelavagod Před rokem

      ​@@me-zu3gm how u know😂

  • @williamselinder9138
    @williamselinder9138 Před 5 měsíci +4

    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!

  • @harshraj22_
    @harshraj22_ Před 2 lety +50

    could have added example of "yield from" as well.
    A great coding exercise would be, print inorder traversal of binary tree using generators.

    • @TechWithTim
      @TechWithTim  Před 2 lety +19

      Great idea!

    • @xx-jk1iq
      @xx-jk1iq Před 2 lety +11

      ok please explain what "inorder traversal of binary tree" is

    • @gregfrost8399
      @gregfrost8399 Před 2 lety +2

      @@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.

    • @xx-jk1iq
      @xx-jk1iq Před 2 lety +2

      @@gregfrost8399 but from what I thought, a binary tree isn't a linear sequence. So how would that work

    • @gregfrost8399
      @gregfrost8399 Před 2 lety +4

      @@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)

  • @gustavocinci4044
    @gustavocinci4044 Před 2 lety +7

    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!

  • @Factory400
    @Factory400 Před 2 lety +6

    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.

  • @saishyam8583
    @saishyam8583 Před 2 lety +19

    I would love to see a video on how you record and edit your videos
    Man This is some real good quality content!!

    • @Mr_Spock512
      @Mr_Spock512 Před 2 lety +3

      Indeed it is, I've learned a ton of stuff from him about Python.

  • @michapodlaszuk9025
    @michapodlaszuk9025 Před 2 lety +8

    good stuff Tim, there's never enough of knowledge about python

  • @vinni113
    @vinni113 Před 2 lety +3

    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!

  • @AleVZero
    @AleVZero Před 2 lety +2

    This channel is just so incredible! i can't tell how much i learned from this channel, thank you

  • @tyrelllaszlo6024
    @tyrelllaszlo6024 Před 2 lety +4

    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👍

  • @NabeelButt
    @NabeelButt Před 2 lety +9

    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!

  • @LNMLucasMasiero
    @LNMLucasMasiero Před 2 lety +2

    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"

  • @fredericoamigo
    @fredericoamigo Před 2 lety +1

    Great video! Best explanation I’ve seen so far on this topic!

  • @bipolarchemist
    @bipolarchemist Před 2 lety +3

    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.

    • @lepidoptera9337
      @lepidoptera9337 Před rokem +1

      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.

  • @TheRealKitWalker
    @TheRealKitWalker Před rokem +1

    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!

  • @STFU665
    @STFU665 Před rokem +2

    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

  • @enzovalendino606
    @enzovalendino606 Před 2 lety +1

    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?

  • @ChromaDotNova
    @ChromaDotNova Před 2 lety +4

    I appreciate the video, Tim! I have a much better understanding of Python generators now.

  • @CaratacusAD
    @CaratacusAD Před rokem +8

    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.

  • @abdullahmohammed6115
    @abdullahmohammed6115 Před 2 lety +1

    Love your vids! Great as always!

  • @ddbarenco
    @ddbarenco Před 2 lety +1

    Amazing explanation! Learn a lot from it. Thank you soo much!!

  • @anirbanc88
    @anirbanc88 Před 2 lety +1

    i love your videos man, and your clarity of explanations, carry on!

  • @MissingTricks
    @MissingTricks Před rokem

    This video provides a clear image of how it works. Thank you.

  • @gustavojuantorena
    @gustavojuantorena Před 2 lety

    This video has so much value! Thank you

  • @network_noob
    @network_noob Před 2 lety

    Now i can finally understand generators! Thanks Tim!!

  • @rodrigo2112-
    @rodrigo2112- Před rokem +1

    You're a great teacher, congrats!

  • @omarelsebaey9589
    @omarelsebaey9589 Před 2 lety

    the example for the generator is perfect , thanks!!!

  • @vammy55
    @vammy55 Před 2 lety

    Great stuff mate,thank you and cheers!

  • @estebangarro7254
    @estebangarro7254 Před rokem

    Excellent Video, thanks!

  • @ChandanSingh-bh7wu
    @ChandanSingh-bh7wu Před 2 lety

    ******BEST GENERATOR EXPLAINATION********** read 3 books + 4 online tutorials, still confused about Generators******* Finally, got it ............!!!! Awesome Brother !!!!!

  • @onlyforscience8255
    @onlyforscience8255 Před 2 lety

    I learned new things which don't know anything about that. Thanks to make such a nice video for us. ☺️☺️👏👏

  • @parvishrao6414
    @parvishrao6414 Před 2 lety

    Tons thanks, only video which clearly said what is iterator and generator - CRYSTAL CLEAR.

  • @manishsingh900
    @manishsingh900 Před 2 lety

    It really is a great video. Thank you!!!!. One of the best generators video generated🙂.

  • @davidring5071
    @davidring5071 Před 2 měsíci

    Amazing video Tim. Thank you

  • @eddywang5035
    @eddywang5035 Před 2 lety

    Useful tutorial for me. Thanks.

  • @NearLWatson
    @NearLWatson Před rokem

    Great job breaking it down 👍🏼

  • @danielmarx3106
    @danielmarx3106 Před 2 lety +2

    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.

  • @Barejs
    @Barejs Před 2 lety +1

    awesome content, keep up with these videos Tim

  • @amalkrishnas1696
    @amalkrishnas1696 Před rokem

    Thanks for the video, well explained

  • @Mdroudian
    @Mdroudian Před 2 lety +1

    Great video. You have a good format. Don't change it =)

  • @boooringlearning
    @boooringlearning Před 2 lety

    thats brilliant video!

  • @elitearmedforce
    @elitearmedforce Před 2 lety +1

    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,

  • @JaBoss397
    @JaBoss397 Před rokem

    Thank you !!

  • @alexandruteodor3585
    @alexandruteodor3585 Před 6 měsíci

    Thank you!

  • @berkaybb5733
    @berkaybb5733 Před 2 lety +1

    Could you make a video about Web scraping by using requests and beautifulsoup modules?And maybe some decorators would be great : )

  • @antmitchell9930
    @antmitchell9930 Před 2 lety +2

    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.

    • @whatdoiputhere5089
      @whatdoiputhere5089 Před 2 lety

      yeah, he should've done that so everyone can know when is the 'Pause 1' getting printed

    • @user-zb8tq5pr4x
      @user-zb8tq5pr4x Před 2 lety

      but the execution pauses after the yield, so pause 1 before makes no sense.

  • @johnnytoobad7785
    @johnnytoobad7785 Před 2 lety

    Looking forward to "Learning Cobol with Tim" course !

  • @yoyokoko5153
    @yoyokoko5153 Před 2 lety

    Thanks for the good stuff

  • @servantofourlordjesuschris6456

    Thanks!

  • @aryankathawale9269
    @aryankathawale9269 Před 2 lety

    lets goo new tech with tim

  • @Tussu17
    @Tussu17 Před 2 lety

    Thank you genius!

  • @thaimeuu
    @thaimeuu Před 5 měsíci

    thank you, Tim

  • @grantpeterson2524
    @grantpeterson2524 Před rokem

    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?

  • @UgochukwuEzeani-ut6vd
    @UgochukwuEzeani-ut6vd Před 5 měsíci

    Awesome 🎉

  • @nicholas_obert
    @nicholas_obert Před 2 lety +6

    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.

    • @hossumquat
      @hossumquat Před 2 lety

      Yes, this would be nice. Does Tim know C though? If so, I've love to learn how to integrate C and Python

    • @nicholas_obert
      @nicholas_obert Před 2 lety

      @@hossumquat he has made a series about C++, plus C is very easy at a beginner level.

    • @hossumquat
      @hossumquat Před 2 lety

      @@nicholas_obert Ah, ok, didn't know that. I'd guess he already knows this then and could teach it. Awesome!

  • @robinferizi9073
    @robinferizi9073 Před 2 lety +1

    I like how the first generator example is literally obscolete because you used for i in range: to say for i in range:

  • @haneulkim4902
    @haneulkim4902 Před 10 měsíci

    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__()?

  • @korkunctheterrible4302

    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.

  • @robinbreed2439
    @robinbreed2439 Před rokem

    super good

  • @wubangzheng
    @wubangzheng Před 2 lety

    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
      @wubangzheng Před 2 lety

      i did some python projects as well like creating a simple alien invasion game

    • @Plepple
      @Plepple Před 2 lety +2

      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

  • @alexramirez5104
    @alexramirez5104 Před 2 lety

    Damn I love this channel

  • @bradyb2415
    @bradyb2415 Před 9 měsíci

    First time i understood what you are saying....☺

  • @barbaraulitsky8292
    @barbaraulitsky8292 Před 2 lety

    This is a super tutorial! Super helpful and clear explanation! Tim, you are awesome! Thank you so much!!!

  • @georgianabhishek3561
    @georgianabhishek3561 Před 2 lety +2

    Please make a pygame video explaining sprites

  • @innocentharelimana4449
    @innocentharelimana4449 Před 2 měsíci

    we, we had teachers who didn't know these stuff😂😂😂, and graduated without this knowledge😊😊😊

  • @Kema109
    @Kema109 Před 10 měsíci

    @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?

  • @lukaszno8988
    @lukaszno8988 Před 2 lety

    Hi Tim can you explain interface in python?

  • @mufasaruleroftheanimalking1026

    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.

  • @jphvnet
    @jphvnet Před rokem

    If for loop stops by the exception, it's not clear where gen() raise the exception. Or there is a different logic inside for() .

  • @pabloshi4863
    @pabloshi4863 Před 2 lety

    Could anyone help me of how to show the [Finished in X ms] in the console?

  • @mgmartin51
    @mgmartin51 Před 2 lety

    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?

  • @UgochukwuEzeani-ut6vd
    @UgochukwuEzeani-ut6vd Před 5 měsíci

    Awesome

  • @mohamedelzend2337
    @mohamedelzend2337 Před 2 lety

    what is that code editor tim using ?plzzzzzzz

  • @rekhasurya3536
    @rekhasurya3536 Před 2 lety

    Love your Vids Tim! keep up the good work(hope u heart this!)

  • @amrsalaheldinabdallahhammo663

    Thanks genius :)

  • @Jschmuck8987
    @Jschmuck8987 Před 3 měsíci

    After every explanation: “HOPEFULLY that KINDA makes sense”. Yes bro it makes sense ffs.

  • @elpython3471
    @elpython3471 Před 2 lety

    Hiyo tim! Good tutorial as always!
    Could you think about making more c++ content, and teach us about c++ libraries?

  • @64imma
    @64imma Před rokem

    What text editor are you using?

  • @terryr5713
    @terryr5713 Před 2 lety

    Tim what can I do with a computer science degree except programming!? 👍👉💪

  • @youssefelamrani7905
    @youssefelamrani7905 Před 2 lety

    can you do a video about testing Tim, i heard spaceX is using Python for testing

    • @xx-jk1iq
      @xx-jk1iq Před 2 lety

      what do you mean by testing?

  • @belowasmelashgebremariam

    Nice

  • @SkyFly19853
    @SkyFly19853 Před 2 lety +2

    Thanks for the explanation.
    Btw, are you interested in making a video about Cython ( C amd C++ extension on Python ) ?
    Thank you in advance!

    • @jonathan3488
      @jonathan3488 Před 2 lety

      Yep. I have tried using cython, but encountered IDE errors and performence issues.

    • @SkyFly19853
      @SkyFly19853 Před 2 lety

      @@jonathan3488
      I see...
      Even so, I think it has the potential.

  • @ncmathsadist
    @ncmathsadist Před rokem

    the object returned by open("foo.txt", "r") has an iterator that walks through the file a line at a time.

    • @lepidoptera9337
      @lepidoptera9337 Před rokem

      That's too easy for the man. He needs to make things complicated. ;-)

  • @neerajvaradi8505
    @neerajvaradi8505 Před 2 lety

    How your code showing the run time..?

  • @tcgvsocg1458
    @tcgvsocg1458 Před 2 lety

    Can you create a "screen recorder"app on python please

  • @ilyasseidkhebbach3812

    good

  • @stele339
    @stele339 Před rokem

    Хвала!

  • @HarryBGamer2570
    @HarryBGamer2570 Před rokem

    what's that font (name?)

  • @Aidanbaro
    @Aidanbaro Před měsícem

    Hi Tim

  • @avigupta6064
    @avigupta6064 Před 2 lety

    Tell me your theme and color of vs code pleaseeee🥺

    • @error2839
      @error2839 Před 2 lety

      He’s not using vs

    • @avigupta6064
      @avigupta6064 Před 2 lety

      @error i know, i am just talking in general like that spotify api tutorial he did.

  • @malanbandara
    @malanbandara Před 2 lety +1

    This guy is almost like Mark Z.

  • @laponiec
    @laponiec Před 10 měsíci

    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?

  • @comedyclub333
    @comedyclub333 Před 2 lety +2

    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.

    • @gagansai8880
      @gagansai8880 Před 2 lety

      generators need not rely on existing iterators...
      def upto(x):
      current = 0
      while current

    • @comedyclub333
      @comedyclub333 Před 2 lety

      @@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.

    • @korkunctheterrible4302
      @korkunctheterrible4302 Před 2 lety

      @@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)

  • @jammincoder
    @jammincoder Před 2 lety

    Those 2 thumbs-downers had their computers upside down.

  • @shawnbeans7389
    @shawnbeans7389 Před 2 lety

    tim finally decided to change from monokai

  • @memk
    @memk Před 2 lety

    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

  • @WhiteDevil-yu5ry
    @WhiteDevil-yu5ry Před 2 lety +1

    Hoping For Tim! To give a heart to this comment! :)

  • @abcdxcxd8280
    @abcdxcxd8280 Před 2 lety

    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]”

  • @krishnaramasimha
    @krishnaramasimha Před 2 lety +1

    8th

  • @aryankathawale9269
    @aryankathawale9269 Před 2 lety

    here before 8 comments