21. Generators [Python 3 Programming Tutorials]

codebasics · Beginner ·🛠️ AI Tools & Apps ·7y ago

Key Takeaways

Explains generators in Python, including their use as iterators and the yield statement

Full Transcript

today's topic is generators in Python okay let's begin with what is generated generated 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 iterator 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 first 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 written statement here if this was return CNN I TR will get CNN assigned to it but here okay so I made a mistake so it should be remote control next so if I say I clear 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 so 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 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 a 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 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 remote control next print C if you recall from I trader episode you already learnt there that for loop works on generators so here the remote control next is giving you generator and generator has an ability to be compliant with the for loop so that for loop can iterate over each of these values okay next thing we are going to cover is 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 the 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 yield first number okay and then your a and B becomes so a becomes B so in this skin syntax a is now becoming b and b will become a plus b right that's what it is 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 all I say I want to see if you wanna see 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 and 1 is 3 2 & 3 is 5 and so on and it terminated when it the Fibonacci number exceeded 50 because 31 34 121 is 55 so that's why it exited 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 okay let's debug it using this thing here and initially it will come to this guy and let's see if I do f11 to go into that okay so I am inside this one action now I will just keep on pressing this button to go to next line as you see a zero-based 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 you 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 next execution from this point so a was 0 B was 1 so the next thing that's gonna happen is it will be 1 and B will be 1 and again I'm going to return yi e so the value of a is now 1 so when you so ucf is 1 now okay and if you look at your console 1 so if you do the next next you'll see C 0 and 1 cut printed here so I will again go inside this and he is now 1 and B is 2 is returning a which is 1 if you just do Afton 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 let me just terminate the 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 an ITR method here you don't need to do that second thing is you don't need to raise top iteration because it will do it automatically for you if I open either once again and let me show the same example just to kind of highlight what I what I mean but you don't need to race stop hydration so here ITR is remote control and IPR so you see it's stopped by iteration here it automatically raises it for you you didn't raise it here right so these are the benefits of generators so that's about it and thank you very much for watching this video

Original Description

Generators are functions that can be used as iterators. Learn more about them in this tutorial. Code used in this tutorial: Exercise: https://github.com/codebasics/py/blob/master/Basics/Exercise/21_generators/21_generators.md Next Video: 22. List Set Dict Comprehensions [Python 3 Programming Tutorials]: https://www.youtube.com/watch?v=fz2PKpPdlRo&list=PLeo1K3hjS3uv5U-Lmlnucd7gqF-3ehIh0&index=24 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. Website: http://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 · 0 of 60

← Previous Next →
1 Python Tutorial - 1. Install python on windows
Python Tutorial - 1. Install python on windows
codebasics
2 Python Tutorial - 2. Variables
Python Tutorial - 2. Variables
codebasics
3 Python Tutorial - 3. Numbers
Python Tutorial - 3. Numbers
codebasics
4 Python Tutorial - 4. Strings
Python Tutorial - 4. Strings
codebasics
5 Python Tutorial - 5. Lists
Python Tutorial - 5. Lists
codebasics
6 Python Tutorial - 6. Install PyCharm on Windows
Python Tutorial - 6. Install PyCharm on Windows
codebasics
7 PyCharm Tutorial - 7. Debug python code using PyCharm
PyCharm Tutorial - 7. Debug python code using PyCharm
codebasics
8 Python Tutorial -  8. If Statement
Python Tutorial - 8. If Statement
codebasics
9 Python Tutorial - 9. For loop
Python Tutorial - 9. For loop
codebasics
10 Python Tutorial -  10. Functions
Python Tutorial - 10. Functions
codebasics
11 Python Tutorial - 11. Dictionaries and Tuples
Python Tutorial - 11. Dictionaries and Tuples
codebasics
12 Python Tutorial - 12. Modules
Python Tutorial - 12. Modules
codebasics
13 Python Tutorial - 13. Reading/Writing Files
Python Tutorial - 13. Reading/Writing Files
codebasics
14 How to install Julia on Windows
How to install Julia on Windows
codebasics
15 Python Tutorial - 14. Working With JSON
Python Tutorial - 14. Working With JSON
codebasics
16 Julia Tutorial - 1. Variables
Julia Tutorial - 1. Variables
codebasics
17 Julia Tutorial - 2. Numbers
Julia Tutorial - 2. Numbers
codebasics
18 Python Tutorial - 15. if __name__ == "__main__"
Python Tutorial - 15. if __name__ == "__main__"
codebasics
19 Julia Tutorial - Why Should I Learn Julia Programming Language
Julia Tutorial - Why Should I Learn Julia Programming Language
codebasics
20 Python Tutorial  - 16. Exception Handling
Python Tutorial - 16. Exception Handling
codebasics
21 Julia Tutorial - 3. Complex and Rational Numbers
Julia Tutorial - 3. Complex and Rational Numbers
codebasics
22 Julia Tutorial - 4. Strings
Julia Tutorial - 4. Strings
codebasics
23 Python Tutorial -  17. Class and Objects
Python Tutorial - 17. Class and Objects
codebasics
24 Julia Tutorial - 5. Functions
Julia Tutorial - 5. Functions
codebasics
25 Julia Tutorial - 6. If Statement and Ternary Operator
Julia Tutorial - 6. If Statement and Ternary Operator
codebasics
26 Julia Tutorial - 7. For While Loop
Julia Tutorial - 7. For While Loop
codebasics
27 Python Tutorial  - 18. Inheritance
Python Tutorial - 18. Inheritance
codebasics
28 Julia Tutorial - 8. begin and (;) Compound Expressions
Julia Tutorial - 8. begin and (;) Compound Expressions
codebasics
29 Python Tutorial - 12.1 - Install Python Module (using pip)
Python Tutorial - 12.1 - Install Python Module (using pip)
codebasics
30 Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
codebasics
31 Julia Tutorial - 10. Exception Handling
Julia Tutorial - 10. Exception Handling
codebasics
32 Python Tutorial  - 19. Multiple Inheritance
Python Tutorial - 19. Multiple Inheritance
codebasics
33 Python Tutorial - 20. Raise Exception And Finally
Python Tutorial - 20. Raise Exception And Finally
codebasics
34 Python Tutorial - 21. Iterators
Python Tutorial - 21. Iterators
codebasics
35 Python Tutorial - 22. Generators
Python Tutorial - 22. Generators
codebasics
36 Python Tutorial - 23. List Set Dict Comprehensions
Python Tutorial - 23. List Set Dict Comprehensions
codebasics
37 Python Tutorial - 24. Sets and Frozen Sets
Python Tutorial - 24. Sets and Frozen Sets
codebasics
38 Python Tutorial - 25. Command line argument processing using argparse
Python Tutorial - 25. Command line argument processing using argparse
codebasics
39 Debugging Tips - What is bug and debugging?
Debugging Tips - What is bug and debugging?
codebasics
40 Debugging Tips - Conditional Breakpoint
Debugging Tips - Conditional Breakpoint
codebasics
41 Debugging Tips - Watches and Call Stack
Debugging Tips - Watches and Call Stack
codebasics
42 Python Tutorial - 26. Multithreading - Introduction
Python Tutorial - 26. Multithreading - Introduction
codebasics
43 Git Tutorial 3:  How To Install Git
Git Tutorial 3: How To Install Git
codebasics
44 Git Tutorial 1: What is git / What is version control system?
Git Tutorial 1: What is git / What is version control system?
codebasics
45 Git Tutorial 2 : What is Github? | github tutorial
Git Tutorial 2 : What is Github? | github tutorial
codebasics
46 Git Tutorial 4: Basic Commands: add, commit, push
Git Tutorial 4: Basic Commands: add, commit, push
codebasics
47 Git Tutorial 5: Undoing/Reverting/Resetting code changes
Git Tutorial 5: Undoing/Reverting/Resetting code changes
codebasics
48 Git Tutorial 6: Branches (Create, Merge, Delete a branch)
Git Tutorial 6: Branches (Create, Merge, Delete a branch)
codebasics
49 Git Github Tutorial 10: What is Pull Request?
Git Github Tutorial 10: What is Pull Request?
codebasics
50 Git Tutorial 7: What is HEAD?
Git Tutorial 7: What is HEAD?
codebasics
51 Git Tutorial 9: Diff and Merge using meld
Git Tutorial 9: Diff and Merge using meld
codebasics
52 Difference between Multiprocessing and Multithreading
Difference between Multiprocessing and Multithreading
codebasics
53 Python Tutorial - 27. Multiprocessing Introduction
Python Tutorial - 27. Multiprocessing Introduction
codebasics
54 Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
codebasics
55 Git Tutorial 8 - .gitignore file
Git Tutorial 8 - .gitignore file
codebasics
56 Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
codebasics
57 Python Tutorial - 30. Multiprocessing Lock
Python Tutorial - 30. Multiprocessing Lock
codebasics
58 Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
codebasics
59 What is code?
What is code?
codebasics
60 Python unit testing - pytest introduction
Python unit testing - pytest introduction
codebasics

Related AI Lessons

Up next
I Asked ChatGPT to Apply to 500 Jobs (8 Interviews in 48 Hours)
Sabrina Ramonov 🍄
Watch →