# Python Coding Problem: Creating Your Own Iterators

## Метаданные

- **Канал:** Corey Schafer
- **YouTube:** https://www.youtube.com/watch?v=C3Z9lJXI6Qw
- **Дата:** 24.10.2018
- **Длительность:** 13:47
- **Просмотры:** 72,703

## Описание

In this Python Coding Problem, we will be creating our own iterators from scratch. First, we will create an iterator using a class. Then we will create an iterator with the same functionality using a generator. If you haven't watched the tutorial video on Iterators and Iterables then I would suggest watching that first...

Iterators and Iterables Tutorial:
https://youtu.be/jTYiNjvnHZY

The code from this video can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python/Iterators-Coding-Problem


✅ Support My Channel Through Patreon:
https://www.patreon.com/coreyms

✅ Become a Channel Member:
https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join

✅ One-Time Contribution Through PayPal:
https://goo.gl/649HFY

✅ Cryptocurrency Donations:
Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot

✅ Corey's Public Amazon Wishlist
http://a.co/inIyro1

✅ Equipment I Use and Books I Recommend:
https://www.amazon.com/shop/coreyschafer

▶️ You Can Find Me On:
My Website - http://coreyms.com/
My Second Channel - https://www.youtube.com/c/coreymschafer
Facebook - https://www.facebook.com/CoreyMSchafer
Twitter - https://twitter.com/CoreyMSchafer
Instagram - https://www.instagram.com/coreymschafer/

#Python

## Содержание

### [0:00](https://www.youtube.com/watch?v=C3Z9lJXI6Qw) Intro

hey there how's it going everybody in this video I'm going to try something a bit different so I've had a lot of requests for me to provide some practice problems alongside my tutorials so that people can practice what they've learned so that's what I'm going to try to do with these videos so the plan is that I'll occasionally release a coding problem video alongside a tutorial so that you can practice what you've learned and see my solution now the reason that I'm making these videos separate instead of just adding the code and problem to the tutorial video is because I want to keep the tutorials separate from the problems so that the tutorial videos don't get excessively long and I also want the problems to be optional so for those who feel like you don't need to practice these things that we've learned in the videos then you can simply skip these coding problem videos so with that said let me know what you all think about this new thing that I'm trying out I love your all's feedback and I want to make sure that most of you think that this is going to be beneficial so I'll definitely monitor the comments and feedback on this video to see if it's something that I want to continue doing but with that said let's go on with the coding problem for this video so this coding problem is going to be about iterators and iterables now if you haven't watched a tutorial i released on iterators and iterables then I highly recommend that you watch that video first so I'll leave a link to that video in a description section below so after you've watched that video then you should have a pretty good understanding of how iterators and iterables work and also how we can create our own using either a class or a generator so in this video let me give you an example problem that you can try to solve and if you want you can pause the video before I give you my solutions so let's say that we want to create a sentence object where we expect a string of words and when we loop over the sentence we simply want to loop over the words in the sentence now let's keep it simple and not worry about punctuation or anything like that for the time being so let's just split the sentence up based on spaces alone so let's first create a sentence class that does this and then let's do the same thing by creating a sentence generator function

### [2:00](https://www.youtube.com/watch?v=C3Z9lJXI6Qw&t=120s) Solution

so for example for the class that should look like this so I can just say my sentence is equal to and we're going to create this class and then we can just pass in a simple sentence and then we can do a that says forward in my sentence print out the word now that should have the following output it should just loop through and say this is a test so it just looped through and printed out one word at a time from that sentence so again for the coding problem I would like you to create a class that has this functionality and then I would also like you to create a generator that has this functionality so if you want to pause the video and give that a try then you can go ahead and do that now but with that said then let me go ahead and show you my solution to this problem so I'm going to come up to the top here and create this sentence class so I'll say class sentence and first I'll create and a knit method so I'll say double underscore a knit and we want to pass in self for the instance and then we also want to pass in a sentence and now we can simply create a class attribute from this so I'll say self dot sentence is equal to sentence and now if you remember what I said in the iterators tutorial an iterator is an object with a state so that it remembers where it is during its iteration so in order to keep track of where we currently are in our loop let's add in an index attribute so I'm going to say self dot index is equal to zero and we'll see how I'm gonna use this in just a minute okay and now we also need to have our list of words that we're going to iterate over so we can get the words from the sentence just by saying so I'll say self dot words is equal to self dot sentence dot split now if you've never used the split method on a string basically it splits the string into a list based on a specific delimiter by default it splits the string by spaces which is what we want in this tutorial but if you wanted to split the string on some other delimiter then you could just pass that in as an argument okay and now to make this class interval we need to create a dunder itter method and that method has to return an object that has a dunder next method so we're going to create the dunder next method on this class itself so we can simply return self from dunder itter so I can say dunder underscore it er look let me fix that there so we can create an inter method here and we can simply return self because this class itself is going to have that dunder next method okay and finally we need to create that dunder next method now this is what is going to return the next word in the sentence and if it doesn't have any more words then we can raise a stop iteration exception so we will create this by saying def double underscore next and we will take self as an argument there and now we need the logic for returning the next word in the sentence and if there are no more words then we need to raise a stop iteration exception so the way I'm going to do this is I'll just say if self dot index is greater than or equal to the length of our self dot words list if our index is greater than or equal to the length of that list then it means that we have looped through all of those values already so we can simply raise stop iteration exception and now if it doesn't raise that stop iteration then we want to return the current word of the index that we are on but we also want to increment the index so that we go to the next word the next time through this next function so the way that I'm going to do this is I'm just going to create a temporary variable here and just say index is equal to self dot index and now we will increment self dot index so I'll say self dot index plus equals 1 and now we will return self dot words and we want to return the index here that we set to the previous value so let me save that so let me run through this one more time so that it's clear what I'm doing here so the first time that we run through this self dot index is going to be equal to zero so it's going to come in and say if zero is greater than or equal to length of self dot words and if we're using our example down here then that's going to be for words so this is not going to be true so it's not going to raise that stop iteration and then it's going to say index is equal to self dot index which will set this equal to zero then we're going to increment self dot index by one so then self dot index will be one and then we're going to return the self dot words at the index of zero because remember this index is zero it's only self done index that is now one so the first time through this is going to return the zero index of self dot words which will be the first word the next time through that self dot index is now equal to 1 because we incremented it and then it's just going to keep looping through that returning the next word until it finally says our until our index is higher than the length of our list and then it's going to raise that stop iteration exception so hopefully that makes sense okay so with that class created we should be able to run the test code that we wrote before and it should loop over the words in that sentence let me make the text just a little smaller here to see if we can fit all this on one screen okay so here's the test code that we had before we're saying my sentence is equal to a new instance of our sentence class and we're passing in this sentence of this is a test and now we're looping over this my sentence variable and

### [8:00](https://www.youtube.com/watch?v=C3Z9lJXI6Qw&t=480s) Testing

printing out those words and the output I said should be you know the first word second word third word fourth word so if I run this then we can see that worked it ran through our for loop and printed out the words one at a time so since we were able to use that in a for loop it means that our object is iterable but it is also an iterator because it has a next method so if we only wanted one word at a time then we could just print out the next variable from my sentence so if I comment this out then we can simply say print next and we will just print out the next value from my sentence oops let me copy that and paste that there and let me do this a couple of times actually and run that and we can see that since we print it out next two times that it printed out the first two words now if I was to do this five times there are only four words so if I did this five times then we should loop through our entire sentence and then hit a stop iteration exception so if I run that then scroll up then we can see that we loop through the entire sentence and then this last part here we hit an error of our stop iteration now that's expected because we're trying to get the next value manually whenever we use a for loop it catches that stop iteration exception for us and it doesn't show us that but when we do it manually we should see that so that's working as it should okay so now I'm going to comment those out and scroll up a little bit and uncomment out my for loop here okay so hopefully you got something working there even if your solution was a little different than mine you probably could have used a try except block here within the next method as well as long as you got it working and it was able to loop through with the for loop and then hit that stop iteration exception when you tried to you know do more than the words that were in the sentence then that should be a good solution okay so now that we've created a class let's now try to create a generator function that does the same thing now I actually think that generators are a lot more simple since they take care of the inner and next methods for us so if you want to try to write a generator function that does the same thing as our class then you can pause the video and do that now but with that said here is my solution to writing this generator so I'm going to put this right underneath the class here so let me scroll down a little bit and now remember this is going to be a generator function so we'll do a function with def and I'm just going to call this sentence with a lowercase s to differentiate it between our class now we'll pass in a parameter here of sentence and for this generator I'm just gonna simply do a loop in here and say for word in sentence dot split and then I'm going to yield the word and our generator it should be as simple as that so what we're doing here is taking in our sentence and then we are saying forward in sentence not split and by default I said that splits on a space and that's going to return a list of words and since we're looping over that we are just yielding each word one at a time and when there are no more words to loop over then it will automatically take care of that stop iteration exception for us so now let's test this so instead of using our class sentence here let's instead use our generator function so I will lowercase that so that we're now using this generator instead and now we are looping over my sentence here so it should print out one word at a time here so if I run that then you can see that we get one word at a time so that's good let me comment out that and uncomment our print statements here to make sure that our next functions are still working so if I save that and run it then sometimes this runs out of order for some reason in sublime text but now we can see that it loops through those first four words and on the fifth word we get this stop iteration exception okay so it looks like that generator function is working the way that we want it to now I think that those generators are a lot easier to write than these custom classes but depending on your use case you might need to know how to do the inner method and the next method on a class as well but I find myself using generators a lot more than these inner and next methods just because of how simple they are okay so let me close out of the output there and scroll up here to the top okay so that's going to do it for this coding problem now if any of you have any different solutions to this problem then let me know in the comments section below I'd be interested to see what you came up with now I'll have my code available on github if you'd like to have a look and I'll leave a link to that in the description section below and also be sure to let me know what you think about these coding problem videos and if you'd like to see more of these alongside other tutorials in the future other than that if anyone has any questions about what we covered then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoy these tutorials and would like to support them then there are several ways you can do that these ways to simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching

---
*Источник: https://ekstraktznaniy.ru/video/12063*