Python Tutorial - 22. Generators
Key Takeaways
Builds a generator using Python's yield statement
Full Transcript
hello and welcome to coal basics coding tutorial today's topic is generators in Python and here is the list of items we are covering in this video ok let's begin with what is generator generating is a simple way of creating an iterator now if you don't know what I traitor is then you can go and watch my last episode on Ike laters in this video as well we are going to cover the AI traitor or real quick so let's say you are defining a remote-control class which when you say remote-control next it gives you the next TV channel so in order to do that you can use this yield statement here so what I'm doing is forced returning CNN then returning ESPN so these are the list of channels that I have on my TV and by calling this remote control next I traitor I am basically going through this channels one by one now this yield statement sounds similar to return but it's not exactly return because the difference between return and yield is that when you return the function basically returns and it destroys all its local variables and so on vs here you will see in a moment that it kind of preserves the state of last execution so if I say I TR equal to remote control C normally if I had return statement here if this was return CNN I TR will get CNN assigned to it but here okay mistake so it should be remote control next so if I say idea here it is telling me idea is a generator object so it is a generator which is basically it's creating an iterator for you when you have I traitor the common property of I traitor is you should be able to do next on it so when you say next you get CNN when you do when you do next again you get ESPN this way when you call next it returns the first yield then it remembers that it was here last time so when you call next second time it is going to return ESPN this could be useful if you have a long list of values and you don't want to return them in one shot because if you return them in one shot it requires lot of memory and also you have to process those values here in this function versus with yield you can produce your first result which is your which is CNN in this case and you can just immediately return it then you can produce the next result result return it so it has a benefit of saving memory as well as getting a quick processing you can also do this so for C in a remote control next prynt see our if you recall from i trader episode you already learned that that for loop works on generators so here remote control necks is giving you a generator and generator has an ability to be compliant with the for loop so that for loop can i trait over each of these values okay our next thing we are going to cover is a Fibonacci sequence we are going to produce that using a generator now before we go into details let's see what a Fibonacci sequence is real quick our Fibonacci sequence is basically a sequence of numbers where you basically keep on adding initial two numbers to get the third number so in this case the initial two numbers is 0 1 so add 0 plus 1 is 1 1 plus 1 2 1 + 2 3 2 + 3 5 and so on so this is call a Fibonacci sequence and what you want to do here is produce Fibonacci sequence using a generator so we are going to write our generator function let's call it fib and the first two numbers in Fibonacci sequence are always 0 and 1 so I just initialized a and B to be 0 and 1 so a here is 0 B is 1 and I'm just going to have an infinite loop here and on each iteration what you do is you healed first number okay and then your a and B becomes a becomes B so in the skins index a is now becoming b and b will become a plus B right that's what it is up and then what you're going to do here is this is your main code so here in this main code you will say for F in fib now notice what will happen if I just keep on calling this for loop since there is an infinite loop here it will never terminate so I want to produce Fibonacci sequence under certain limit so here I would say if F greater than 30 then break I want to just see Fibonacci or less I I want to see Fibonacci numbers between 0 and 50 okay so all right so let's do this and then print F alright let's quickly run this excellent so you see here I got the Fibonacci sequence 0 1 1 1 1 2 or 2 & 1 is 3 2 & 3 is 5 and so on and it terminated when it the village is number exceeded 50 because 31 34 and 21 is 55 so that's why it exceeded if you want to print like numbers until 100 then you get this so the way this works is we can set up a breakpoint and see how this is going so we're okay let's debug it using this thing here and initially it will come to this guy let's see if I do f11 to go into that okay so I am inside this function now I will just keep on pressing this button to go to next line as you see a zero base one yield so when I do yield so from yield yield is short of like return so it came back here and when you look at the value of f it is zero good go to next statement and again you do next or I would rather step into it so when I step into it it remembers that it executed this statement last time so then it resumed legs execution from this point so a was 0 B was 1 so the next thing that's going to happen is it will be 1 and B will be 1 and again I am going to return e e so the value of a is now 1 so when you so you see f is 1 now okay and if you look at your pencil one so if you don't mix next you see C 0 and 1 cor printed here so I will again go inside this and is now one and B's 2 is turning a which is one so if you just do f10 it will not if you just do actin it will not go inside this function if you want to go inside the function then you have to do f11 all or use this button okay so you kind of get how this works right okay now the generators are better compared to class-based I traitors because you noticed here is the missus terminate execution here so because you notice here is that we didn't need to implement ITR or next methods if you recall from my last video if you are writing a class based hydrator then you have to write next and ITR method here you don't need to do that our second thing is you don't need to raise top iteration because it will do it automatically for you if I open idle once again and let me show you the same example just to kind of highlight what I'm what I mean by it you don't need to raise stop by iteration so here IPR is remote control and matched IPR so you see it's stop iteration here it automatically raises it for you you didn't raise it here right so these are the benefits of generators ah so that's about it and thank you very much for watching this video
Original Description
Video without background music: https://youtu.be/66HNCg7_gfE
This python tutorial will educate us about “generators”. The topics which we will cover in this tutorial are what are generators, how to use generators in python, how to create “yield statement” , how to use it, the difference between yield statement and return and how to use generators for Fibonacci sequence.
Topics that are covered in this Python Video:
0:00 Introduction
0:09 what are generators?
0:42 Create yield statement and how to use it
1:10 yield statement vs return
4:00 Fibonacci sequence using generators
Generators are functions that can be used as iterators. Learn more about them in this tutorial.
Code used in this tutorial: https://github.com/codebasics/py/blob/master/Basics/22_Generators.py
Do you want to learn technology from me? Check https://codebasics.io/ for my affordable video courses.
Next Video:
Python Tutorial - 23. List Set Dict Comprehensions: https://www.youtube.com/watch?v=MxZwyrIXNjs&list=PLeo1K3hjS3usILfyvQlvUBokXkHPSve6S&index=25
Website: https://codebasics.io/
Facebook: https://www.facebook.com/codebasicshub
Twitter: https://twitter.com/codebasicshub
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from codebasics · codebasics · 35 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
▶
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Python Tutorial - 1. Install python on windows
codebasics
Python Tutorial - 2. Variables
codebasics
Python Tutorial - 3. Numbers
codebasics
Python Tutorial - 4. Strings
codebasics
Python Tutorial - 5. Lists
codebasics
Python Tutorial - 6. Install PyCharm on Windows
codebasics
PyCharm Tutorial - 7. Debug python code using PyCharm
codebasics
Python Tutorial - 8. If Statement
codebasics
Python Tutorial - 9. For loop
codebasics
Python Tutorial - 10. Functions
codebasics
Python Tutorial - 11. Dictionaries and Tuples
codebasics
Python Tutorial - 12. Modules
codebasics
Python Tutorial - 13. Reading/Writing Files
codebasics
How to install Julia on Windows
codebasics
Python Tutorial - 14. Working With JSON
codebasics
Julia Tutorial - 1. Variables
codebasics
Julia Tutorial - 2. Numbers
codebasics
Python Tutorial - 15. if __name__ == "__main__"
codebasics
Julia Tutorial - Why Should I Learn Julia Programming Language
codebasics
Python Tutorial - 16. Exception Handling
codebasics
Julia Tutorial - 3. Complex and Rational Numbers
codebasics
Julia Tutorial - 4. Strings
codebasics
Python Tutorial - 17. Class and Objects
codebasics
Julia Tutorial - 5. Functions
codebasics
Julia Tutorial - 6. If Statement and Ternary Operator
codebasics
Julia Tutorial - 7. For While Loop
codebasics
Python Tutorial - 18. Inheritance
codebasics
Julia Tutorial - 8. begin and (;) Compound Expressions
codebasics
Python Tutorial - 12.1 - Install Python Module (using pip)
codebasics
Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
codebasics
Julia Tutorial - 10. Exception Handling
codebasics
Python Tutorial - 19. Multiple Inheritance
codebasics
Python Tutorial - 20. Raise Exception And Finally
codebasics
Python Tutorial - 21. Iterators
codebasics
Python Tutorial - 22. Generators
codebasics
Python Tutorial - 23. List Set Dict Comprehensions
codebasics
Python Tutorial - 24. Sets and Frozen Sets
codebasics
Python Tutorial - 25. Command line argument processing using argparse
codebasics
Debugging Tips - What is bug and debugging?
codebasics
Debugging Tips - Conditional Breakpoint
codebasics
Debugging Tips - Watches and Call Stack
codebasics
Python Tutorial - 26. Multithreading - Introduction
codebasics
Git Tutorial 3: How To Install Git
codebasics
Git Tutorial 1: What is git / What is version control system?
codebasics
Git Tutorial 2 : What is Github? | github tutorial
codebasics
Git Tutorial 4: Basic Commands: add, commit, push
codebasics
Git Tutorial 5: Undoing/Reverting/Resetting code changes
codebasics
Git Tutorial 6: Branches (Create, Merge, Delete a branch)
codebasics
Git Github Tutorial 10: What is Pull Request?
codebasics
Git Tutorial 7: What is HEAD?
codebasics
Git Tutorial 9: Diff and Merge using meld
codebasics
Difference between Multiprocessing and Multithreading
codebasics
Python Tutorial - 27. Multiprocessing Introduction
codebasics
Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
codebasics
Git Tutorial 8 - .gitignore file
codebasics
Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
codebasics
Python Tutorial - 30. Multiprocessing Lock
codebasics
Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
codebasics
What is code?
codebasics
Python unit testing - pytest introduction
codebasics
Related Reads
📰
📰
📰
📰
AI-Ready Infrastructure: A Checklist Before You Scale
Dev.to AI
How I Cut My OpenAI Bill by 97% — The Full Migration Guide
Dev.to · rarenode
Your Website Passed Claude’s Search Test. It Might Still Fail the Other Two
Medium · AI
AI Made Creation Free. Taste Is What's Scarce Now
Forbes Innovation
Chapters (5)
Introduction
0:09
what are generators?
0:42
Create yield statement and how to use it
1:10
yield statement vs return
4:00
Fibonacci sequence using generators
🎓
Tutor Explanation
DeepCamp AI