#28: Iterators in Python | Python for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
iterators are everywhere in python they are elegantly implemented within for loops list and dictionary comprehensions but they are hidden in plain sight in this video we will learn about iterables and iterators in python with the help of examples we will also create our own custom iterator and see how the for loop actually works we've got a lot to cover so let's get started before we learn about iterators let's first understand what an iterable is basically anything that you can loop over in python is called an iterable for example a list is an iterable for an object to be considered an iterable it must have the iter or iter method let's check if lists have this special method to check this i will use the dir function which returns all the methods of an object so here on my code editor i'll say print dir numbers now let me run this code and here among all these methods you can see the dunder itr method let's call this method on this numbers list to see what it does so here i'll say value equals numbers dot dunder or double underscore iter double underscore and let me print the value when i press run then you can see that we got a list iterator object and this is the memory location of that object next we will see what iterator objects are iterator in python is simply an object that can return data one at a time while iterating over it for an object to be an iterator it must implement two methods iter or iter and next these are collectively called the iterator protocol now we'll look into the next method in detail suppose we have a list like this so i'll say numbers equals 1 comma 4 comma 9. now i'll get an iterator from this list using the iter method so here i'll say value equals numbers dot dunder or double underscore under iter and next here this variable value is an iterator and we can get each element of this iterator by using the next method the next method returns the next value in the iteration so here i can say item 1 equals value dot double underscore or dunder next and then i can print item one when i run this code then one which is the first element of this list is printed now if i run the next method again it should return the next item which is four it's because the next method also updates the state of the iterator and here i'll say item two equals value dot done next print item 2 and then item 3 equals value.next and then i'll say print item 3. now let me run this code as you can see first one was printed then four then nine by the way instead of calling these special methods with an underscore python has an elegant way to call underscore underscore iter simply with the iter function and underscore underscore next underscore underscore with the next function i'll make these changes to my previous code so here instead of calling numbers dot underscore underscore iter i can say iter numbers and instead of calling value dot underscore underscore next underscore underscore i can say next value here to i can say next value and here as well next value when i run this code i get the same output as before but my code looks a lot cleaner than before by the time i get to the third element we have already reached the end of our list now let's see what happens if we further try to get the next value so here i'll say item 4 equals next value and let me try to print item 4. now when i run the code then you can see that the stop iteration exception has been raised since our list had only three elements the call to the fourth next method raised the stop iteration exception did you know that for loops internally use the while loop to iterate through sequences to demonstrate this let me first look through a list using the while loop so i'll go to my code editor and create a new list i'll say num underscore list equals 1 comma 4 comma 9 and now let me create an iterator object so here i'll say iter underscore obj or iterator object equals iter num underscore list here the iter object is an iterator we can now use an infinite while loop to get the next element using the next method and in case of stop iteration exception occurs we will break out of this loop so here i'll say while true and then i can say try try to get the next next element so next item underscore obj and then if i get the element print that element now if there is an exception then i can say or if there's more specifically i'll say if there's an stop iteration exception then break the code here's how this code works first we have created an iterator object from a list using the iter function then we have created an infinite while loop inside the loop we have used the next method to get the next element in the sequence in the next line we have printed that element we have put all this code inside a try block and when all the items of the iterator are iterated the try block raises the stop iteration exception and we break out of the loop let me run this code and you can see that 1 4 and 9 have been printed in fact this is exactly how for loops work behind the scenes a for loop internally creates an iterator object and iterates over it calling the next method until the stop iteration exception is encountered by the way if you're finding this video useful a sub to the channel would be much appreciated before moving to the next section of the video the programming team has created an app that allows you to learn python from your phone the app contains bit size lessons that are easier to understand a built-in interpreter so that you can run python on your phone quizzes and many more the app is available on both ios and android the links are in the video description as we have already seen iterators are simply objects that implement the item method and the next method let's try to make our own iterator object here we'll create a program that will generate a sequence of even numbers such as 2 4 6 8 and so on for this i'll create a class with the init method so let me remove this old code and here i'll say class even and inside this let me start by creating the init method so i'll say def underscore underscore init underscore underscore self and max and then let me initialize self dot n equals 2 so that's the first value which is always 2 and self.max is the value that we provide by now we already know that iterators must implement an item method which returns an iterator so i'll simply create an item method that returns the object itself so here i'll say def underscore underscore iter underscore underscore self and here i'll say return self now let's implement the next method this method should give the next element in the stream if it exists if the next element is not available it should raise the stop iteration exception so here i'll say def underscore underscore next underscore underscore oops i forgot a bracket here self and here inside this method we want to generate a sequence up to the max number and if the next element exceeds max we will raise an exception so let me first start with the framework of the code here if self dot n as long as it is less than self.max then we need to do one thing and else we need to raise the stop iteration exception now inside this if i need to generate the next number in the sequence so here i'll say result equals self dot n i am temporarily saving the current value of n in the result variable now i want to increase the value of n by 2 so here i'll say self dot n plus equals 2 and then return result because i want to return the old value of n not the new one now our class is finally complete let's create an object from this class which is an iterator because it implements both the iter and the next methods so here outside the class i'll say numbers equals even 10. now when i call the next method i should get even numbers one after another let me print three even numbers i'll say print next numbers print next numbers and print next numbers again now when i press run then you can see that 2 4 and 6 are printed if we use the next method three more times the stop iteration exception is raised as of sequence can only have numbers up to 10 because of this limit here at this point we have covered all the basics of iterators in python but you might be wondering why it is used iterators are powerful tools when dealing with the last stream of data if you use regular list to store these values our computer would run out of memory quickly with iterators however we can save resources as they return only one element at a time so in theory we can deal with infinite data in finite memory generally iterators are implemented in python using something called generators that make it much easier to use them we will cover python generators in detail in our next video that's it for this video if you want to revise these concepts you can find all these programs in our github repository i'll also put this link in the video description and if you like this video hit that like button and subscribe to the channel and i'll see you in the next one happy programming you
Info
Channel: Programiz
Views: 17,234
Rating: undefined out of 5
Keywords: #28: Iterators in Python | Python for Beginners, terators in Python, Python for Beginners, programiz, python, learnprogramming, iteratorsinpython, Programiz, programiz python examples, programiz python, python programiz, programiz python programs, programiz python iterators
Id: C_rhipZonok
Channel Id: undefined
Length: 11min 20sec (680 seconds)
Published: Wed Jan 27 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.