Python Tutorial - 22. Generators

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

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 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
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 Reads

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
Up next
Vidx.ai Doesn't Work Like They Claim—Here's Why
DroidCrunch
Watch →