Python Generators Explained

  Рет қаралды 159,775

Tech With Tim

Tech With Tim

Күн бұрын

Пікірлер: 182
@goboy6882
@goboy6882 3 жыл бұрын
I started programming 60 years ago. Thank you Tim for teaching an old dog new tricks.
@Ian-bb7vv
@Ian-bb7vv 3 жыл бұрын
wow, life long learning!!!
@piadas804
@piadas804 3 жыл бұрын
Wow
@JasonJorgensonPhD
@JasonJorgensonPhD 2 жыл бұрын
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.
@ketso-l7b
@ketso-l7b 2 жыл бұрын
Lies!🥱🥱🥱
@thelavagod
@thelavagod Жыл бұрын
​@@ketso-l7b how u know😂
@williamselinder9138
@williamselinder9138 10 ай бұрын
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!
@vinni113
@vinni113 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!
@ChandanSingh-bh7wu
@ChandanSingh-bh7wu 2 жыл бұрын
******BEST GENERATOR EXPLAINATION********** read 3 books + 4 online tutorials, still confused about Generators******* Finally, got it ............!!!! Awesome Brother !!!!!
@gustavocinci4044
@gustavocinci4044 2 жыл бұрын
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 3 жыл бұрын
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.
@tyrelllaszlo6024
@tyrelllaszlo6024 3 жыл бұрын
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👍
@harshraj22_
@harshraj22_ 3 жыл бұрын
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 3 жыл бұрын
Great idea!
@xx-jk1iq
@xx-jk1iq 3 жыл бұрын
ok please explain what "inorder traversal of binary tree" is
@gregfrost8399
@gregfrost8399 3 жыл бұрын
@@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 3 жыл бұрын
@@gregfrost8399 but from what I thought, a binary tree isn't a linear sequence. So how would that work
@gregfrost8399
@gregfrost8399 3 жыл бұрын
@@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)
@saishyam8583
@saishyam8583 3 жыл бұрын
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 3 жыл бұрын
Indeed it is, I've learned a ton of stuff from him about Python.
@MissingTricks
@MissingTricks Жыл бұрын
This video provides a clear image of how it works. Thank you.
@bipolarchemist
@bipolarchemist 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 Жыл бұрын
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.
@NabeelButt
@NabeelButt 2 жыл бұрын
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!
@CaratacusAD
@CaratacusAD Жыл бұрын
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.
@LNMLucasMasiero
@LNMLucasMasiero 3 жыл бұрын
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"
@parvishrao6414
@parvishrao6414 3 жыл бұрын
Tons thanks, only video which clearly said what is iterator and generator - CRYSTAL CLEAR.
@roarba
@roarba 3 жыл бұрын
This channel is just so incredible! i can't tell how much i learned from this channel, thank you
@ChromaDotNova
@ChromaDotNova 2 жыл бұрын
I appreciate the video, Tim! I have a much better understanding of Python generators now.
@omarelsebaey9589
@omarelsebaey9589 2 жыл бұрын
the example for the generator is perfect , thanks!!!
@TheRealKitWalker
@TheRealKitWalker Жыл бұрын
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!
@michapodlaszuk9025
@michapodlaszuk9025 3 жыл бұрын
good stuff Tim, there's never enough of knowledge about python
@fredericoamigo
@fredericoamigo 2 жыл бұрын
Great video! Best explanation I’ve seen so far on this topic!
@STFU665
@STFU665 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
@YEM_
@YEM_ 4 ай бұрын
Best explanation I've heard yet.
@rodrigo2112-
@rodrigo2112- 2 жыл бұрын
You're a great teacher, congrats!
@Adedeji-v9z
@Adedeji-v9z 3 күн бұрын
At 5:29, the range() function is actually an iterable because it doesn't have a _next_ method, only an __iter__method, iterators by default have both the __iter__ and __next__ method, while using for loop, the for loop applies the __iter__ method on range() creating an iterator (specifically a range iterator object), then calls the __next__ method on the iterator object, I guess the range() function just happens to be that iterable which implements memory management efficiently than other iterables like list, tuples, strings.
@network_noob
@network_noob 3 жыл бұрын
Now i can finally understand generators! Thanks Tim!!
@anirbanc88
@anirbanc88 2 жыл бұрын
i love your videos man, and your clarity of explanations, carry on!
@antmitchell9930
@antmitchell9930 3 жыл бұрын
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 3 жыл бұрын
yeah, he should've done that so everyone can know when is the 'Pause 1' getting printed
@user-zb8tq5pr4x
@user-zb8tq5pr4x 2 жыл бұрын
but the execution pauses after the yield, so pause 1 before makes no sense.
@johnnytoobad7785
@johnnytoobad7785 3 жыл бұрын
Looking forward to "Learning Cobol with Tim" course !
@onlyforscience8255
@onlyforscience8255 3 жыл бұрын
I learned new things which don't know anything about that. Thanks to make such a nice video for us. ☺️☺️👏👏
@enzovalendino606
@enzovalendino606 3 жыл бұрын
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?
@ddbarenco
@ddbarenco 3 жыл бұрын
Amazing explanation! Learn a lot from it. Thank you soo much!!
@abdullahmohammed6115
@abdullahmohammed6115 3 жыл бұрын
Love your vids! Great as always!
@NearLWatson
@NearLWatson 2 жыл бұрын
Great job breaking it down 👍🏼
@bradyb2415
@bradyb2415 Жыл бұрын
First time i understood what you are saying....☺
@davidring5071
@davidring5071 7 ай бұрын
Amazing video Tim. Thank you
@danielmarx3106
@danielmarx3106 3 жыл бұрын
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.
@gustavojuantorena
@gustavojuantorena 2 жыл бұрын
This video has so much value! Thank you
@amalkrishnas1696
@amalkrishnas1696 Жыл бұрын
Thanks for the video, well explained
@robinferizi9073
@robinferizi9073 3 жыл бұрын
I like how the first generator example is literally obscolete because you used for i in range: to say for i in range:
@estebangarro7254
@estebangarro7254 Жыл бұрын
Excellent Video, thanks!
@Mdroudian
@Mdroudian 2 жыл бұрын
Great video. You have a good format. Don't change it =)
@vammy55
@vammy55 2 жыл бұрын
Great stuff mate,thank you and cheers!
@bahdcoder
@bahdcoder 3 ай бұрын
You are the best out there man
@lam-thai-nguyen
@lam-thai-nguyen 11 ай бұрын
thank you, Tim
@eddywang5035
@eddywang5035 3 жыл бұрын
Useful tutorial for me. Thanks.
@Barejs
@Barejs 2 жыл бұрын
awesome content, keep up with these videos Tim
@innocentharelimana4449
@innocentharelimana4449 8 ай бұрын
we, we had teachers who didn't know these stuff😂😂😂, and graduated without this knowledge😊😊😊
@manishsingh900
@manishsingh900 3 жыл бұрын
It really is a great video. Thank you!!!!. One of the best generators video generated🙂.
@aryankathawale9269
@aryankathawale9269 3 жыл бұрын
lets goo new tech with tim
@georgianabhishek3561
@georgianabhishek3561 3 жыл бұрын
Please make a pygame video explaining sprites
@berkaybb5733
@berkaybb5733 3 жыл бұрын
Could you make a video about Web scraping by using requests and beautifulsoup modules?And maybe some decorators would be great : )
@alexandruteodor3585
@alexandruteodor3585 Жыл бұрын
Thank you!
@Jschmuck8987
@Jschmuck8987 8 ай бұрын
After every explanation: “HOPEFULLY that KINDA makes sense”. Yes bro it makes sense ffs.
@nicholas_obert
@nicholas_obert 3 жыл бұрын
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 3 жыл бұрын
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 3 жыл бұрын
@@hossumquat he has made a series about C++, plus C is very easy at a beginner level.
@hossumquat
@hossumquat 3 жыл бұрын
@@nicholas_obert Ah, ok, didn't know that. I'd guess he already knows this then and could teach it. Awesome!
@JaBoss397
@JaBoss397 2 жыл бұрын
Thank you !!
@alexramirez5104
@alexramirez5104 3 жыл бұрын
Damn I love this channel
@servantofourlordjesuschris6456
@servantofourlordjesuschris6456 Жыл бұрын
Thanks!
@elitearmedforce
@elitearmedforce 3 жыл бұрын
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,
@mufasaruleroftheanimalking1026
@mufasaruleroftheanimalking1026 6 ай бұрын
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.
@yoyokoko5153
@yoyokoko5153 3 жыл бұрын
Thanks for the good stuff
@boooringlearning
@boooringlearning 3 жыл бұрын
thats brilliant video!
@UgochukwuEzeani-ut6vd
@UgochukwuEzeani-ut6vd 11 ай бұрын
Awesome 🎉
@korkunctheterrible4302
@korkunctheterrible4302 2 жыл бұрын
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.
@GoziePO
@GoziePO 5 ай бұрын
thank you!!!
@robinbreed2439
@robinbreed2439 2 жыл бұрын
super good
@monicakristin8144
@monicakristin8144 4 ай бұрын
tq
@rekhasurya3536
@rekhasurya3536 3 жыл бұрын
Love your Vids Tim! keep up the good work(hope u heart this!)
@Tussu17
@Tussu17 3 жыл бұрын
Thank you genius!
@jphvnet
@jphvnet Жыл бұрын
If for loop stops by the exception, it's not clear where gen() raise the exception. Or there is a different logic inside for() .
@barbaraulitsky8292
@barbaraulitsky8292 2 жыл бұрын
This is a super tutorial! Super helpful and clear explanation! Tim, you are awesome! Thank you so much!!!
@UgochukwuEzeani-ut6vd
@UgochukwuEzeani-ut6vd 11 ай бұрын
Awesome
@ncmathsadist
@ncmathsadist Жыл бұрын
the object returned by open("foo.txt", "r") has an iterator that walks through the file a line at a time.
@lepidoptera9337
@lepidoptera9337 Жыл бұрын
That's too easy for the man. He needs to make things complicated. ;-)
@lukaszno8988
@lukaszno8988 3 жыл бұрын
Hi Tim can you explain interface in python?
@stele339
@stele339 Жыл бұрын
Хвала!
@amrsalaheldinabdallahhammo663
@amrsalaheldinabdallahhammo663 2 жыл бұрын
Thanks genius :)
@haneulkim4902
@haneulkim4902 Жыл бұрын
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__()?
@Aidanbaro
@Aidanbaro 7 ай бұрын
Hi Tim
@wubangzheng
@wubangzheng 3 жыл бұрын
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 3 жыл бұрын
i did some python projects as well like creating a simple alien invasion game
@Plepple
@Plepple 3 жыл бұрын
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
@elpython3471
@elpython3471 3 жыл бұрын
Hiyo tim! Good tutorial as always! Could you think about making more c++ content, and teach us about c++ libraries?
@Kema109
@Kema109 Жыл бұрын
@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?
@ScOrPiOnE905
@ScOrPiOnE905 3 жыл бұрын
I'd like to make a note regarding the execution of generators, maybe somehow it'll be useful to someone. A generator will not re-iterate if it has already finished the range it was given in a variable for example. However, it will re-iterate if you call directly to the generator itself, not the variable you might have assigned it to. You can try this out with a range, a for loop and the print function (I've posted some code below to give an example) Code to try it out for yourselves below (I hope the formatting won't be broken): def generator_example(n: int): print(" Generator has started. ") start = 0 while start < n: print("Generator is returning {}".format(start)) yield start start += 1 range_example = generator_example(5) list_example = [] print(next(range_example)) # Exhausts 1 of the total of 5 values in the range_example variable. input("Press Enter to proceed.") for values in range_example: input() list_example.append(values) # Only 4 values remain to be appended. print() print("Generator has already finished and will not execute the for loop in the code in the same variable (range_example) below.") print("The print(next(range_example)) function will also exhaust one execution of the generator.") for i in range_example: list_example.append(i) print() print("Calling the function itself, however, will execute the for loop however many times you want.") print() for j in generator_example(5): list_example.append(j) for k in generator_example(5): # print(k) list_example.append(k)
@korkunctheterrible4302
@korkunctheterrible4302 2 жыл бұрын
So where is the information for the first next() yield stored, in range_example ? and if it is stored, why does that not take up memory or is it that it just takes smaller memory in comparison? when you call the generator_example function with the argument 5, does the function def block create 5 spots to fill for in the range_example first, and one gets filled by the first "next", and a mark is put in there? does the info for where the mark will go get overwritten in the same space of memory with each execution? lol sorry for my dreadful misuse of any term or anything and I hope you still understand my question (I actually asked about it before I bumped into your explanation, and YT doesn't let me copy any comment from other users, although I will try it out myself later when I'm able but there's a chance that I'll misinterpret somethings) Thank you for your comment btw.
@korkunctheterrible4302
@korkunctheterrible4302 2 жыл бұрын
Also what'd happen if there were no range_example to which to assign generator_example()? it would start from the start like at every call, like you said later in your post right? but I don't remember Tim using another alias like thing, still it picked up where next() left off (4 nexts and then for loop picks up the fifth, at 09:46)
@ilyasseidkhebbach3812
@ilyasseidkhebbach3812 2 жыл бұрын
good
@mohamedelzend2337
@mohamedelzend2337 2 жыл бұрын
what is that code editor tim using ?plzzzzzzz
@SkyFly19853
@SkyFly19853 3 жыл бұрын
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 3 жыл бұрын
Yep. I have tried using cython, but encountered IDE errors and performence issues.
@SkyFly19853
@SkyFly19853 3 жыл бұрын
@@jonathan3488 I see... Even so, I think it has the potential.
@youssefelamrani7905
@youssefelamrani7905 3 жыл бұрын
can you do a video about testing Tim, i heard spaceX is using Python for testing
@xx-jk1iq
@xx-jk1iq 3 жыл бұрын
what do you mean by testing?
@terryr5713
@terryr5713 3 жыл бұрын
Tim what can I do with a computer science degree except programming!? 👍👉💪
@belowasmelashgebremariam
@belowasmelashgebremariam 2 жыл бұрын
Nice
@belowasmelashgebremariam
@belowasmelashgebremariam 2 жыл бұрын
Asme Tchaikovsky climb to uucp
@belowasmelashgebremariam
@belowasmelashgebremariam 2 жыл бұрын
Razed St Ed Sry egg re zed zarathustra ink
@mgmartin51
@mgmartin51 3 жыл бұрын
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?
@neerajvaradi8505
@neerajvaradi8505 2 жыл бұрын
How your code showing the run time..?
@grantpeterson2524
@grantpeterson2524 2 жыл бұрын
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?
@Adedeji-v9z
@Adedeji-v9z 3 күн бұрын
the iterator object also has an __iter__ method and a __next__ method, when a for loop works on an iterator, it calls the __iter__ method of the iterator object, the __iter__ method of the iterator object returns self (the iterator itself), why: since the iterator object is already an iterator it makes sense for the __iter__ method to return the iterator object, after that it calls the __next__ method on the iterator object getting next element in the iterator, Hope that's clear
@pabloshi4863
@pabloshi4863 3 жыл бұрын
Could anyone help me of how to show the [Finished in X ms] in the console?
@64imma
@64imma Жыл бұрын
What text editor are you using?
@entity5678
@entity5678 Жыл бұрын
sublime text
@WhiteDevil-yu5ry
@WhiteDevil-yu5ry 3 жыл бұрын
Hoping For Tim! To give a heart to this comment! :)
@laponiec
@laponiec Жыл бұрын
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?
@malanbandara
@malanbandara 3 жыл бұрын
This guy is almost like Mark Z.
@tcgvsocg1458
@tcgvsocg1458 3 жыл бұрын
Can you create a "screen recorder"app on python please
@edcdecl
@edcdecl 3 жыл бұрын
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]”
@shawnbeans7389
@shawnbeans7389 3 жыл бұрын
tim finally decided to change from monokai
@aryankathawale9269
@aryankathawale9269 3 жыл бұрын
here before 8 comments
Python Object Oriented Programming (OOP) - For Beginners
53:06
Tech With Tim
Рет қаралды 3,4 МЛН
10 Python Shortcuts You Need To Know
27:27
Tech With Tim
Рет қаралды 296 М.
Симбу закрыли дома?! 🔒 #симба #симбочка #арти
00:41
Симбочка Пимпочка
Рет қаралды 4,8 МЛН
ТЫ В ДЕТСТВЕ КОГДА ВЫПАЛ ЗУБ😂#shorts
00:59
BATEK_OFFICIAL
Рет қаралды 4,6 МЛН
За кого болели?😂
00:18
МЯТНАЯ ФАНТА
Рет қаралды 3,1 МЛН
Муж внезапно вернулся домой @Oscar_elteacher
00:43
История одного вокалиста
Рет қаралды 6 МЛН
Python Generators
15:32
mCoding
Рет қаралды 141 М.
Please Master These 10 Python Functions…
22:17
Tech With Tim
Рет қаралды 216 М.
5 Useful Python Decorators (ft. Carberra)
14:34
Indently
Рет қаралды 107 М.
Python Asynchronous Programming - AsyncIO & Async/Await
25:57
Tech With Tim
Рет қаралды 432 М.
How To Write Better Functions In Python
14:17
Indently
Рет қаралды 49 М.
PLEASE Use These 5 Python Decorators
20:12
Tech With Tim
Рет қаралды 122 М.
Write Python Code Properly!
25:46
Tech With Tim
Рет қаралды 148 М.
Asyncio in Python - Full Tutorial
24:59
Tech With Tim
Рет қаралды 97 М.
Python Decorators in 15 Minutes
15:14
Kite
Рет қаралды 452 М.
Симбу закрыли дома?! 🔒 #симба #симбочка #арти
00:41
Симбочка Пимпочка
Рет қаралды 4,8 МЛН