Python Institute PCAP – Control Flow Part 4
- Range, Enumerate, and Zip Functions
Functions. Let’s say that you have a word, for example, let’s just create a variable called word and we’ll say that the word says hello. Okay, if I wanted to take each of these characters and dump them into a list, one way of doing that is actually loop through this list and take those and assign each of these characters, append them to a list object. As we’ve you’ve seen earlier, there’s an append method that you can invoke on a list that’s one way. Another thing is you can use something known as the list function. So if I use this list function and pass in the word to it, now all of a sudden this turns it into a list. So let’s just assign a variable called my list. And now if I was to print my list, you’ll see what it has. So let’s run this and boom. Notice now we have this word in a list format and each character is an item in the list. Pretty cool, right? Similar to this, we’ve got some other functions handy, functions that we need to learn. So we’re going to invest the rest of this lesson exploring those. So you can imagine you could actually loop through this listed word, let’s call it.
So if I was to instead of printing this list, let’s just loop over it. I could just do the for loop and say for letter in and then have this list word function. So this is going to turn this word into a list of letters and then I could just print the letters like this, right? And so this will work as expected. So we essentially turned this word into a list using this list function. What if we want to loop through a bunch of numbers? One way of doing that is I would create, you know, my NUM list or something like that, and then put in a bunch of numbers like 012345 and so on, and then loop through these numbers. That’s one way. Another thing we could use is known as the range function. So let me show you what that looks like. We could do four numb in the range function.
And as an argument to this range function, we pass in the numbers that we want up to, but not including a given number amount. So let’s just say ten. Okay? So what this is going to do is going to loop through zero through nine because this ten is not inclusive. I’ll show you exactly what I mean. Let’s print this and you’ll see what gets printed. So let’s run this. And so notice we got from zero all the way down to nine. If you want the ten to be printed, we of course have to change this to an eleven because again, it loops up to, but not including the number that you give to this argument to the range. So let’s run this. And now we see from zero to ten you can also set a starting point. Let’s say we don’t want zero, we just want a loop through one through ten. How would you do that? Well, you could put one here as the first argument and notice this helper IntelliSense shows up and it’s saying that there’s a start integer, stop integer and there’s also something called a step, which we’ll get into just a moment. But now, instead of it starting from zero, it’s actually going to start from one. OK, so let’s run this and boom. There you go. It started from one all the way up to ten.
All right, we can change this to five, for example, and as you can imagine, it’s going to start from the number five. Now, if I want to, for example, just get even numbers up to ten, I can do a step. So let’s get a starting number of two. So I’ll put two here and then we’ll leave this to eleven. That is the end ending range. So the beginning range is two, the ending range is this and then we can have a step size. So let’s take steps of two and what that’s going to do is going to print 2468 and so on. So let’s run this and boom, there we go. It starts from two, four, 6810. Again, if I change this to ten, this is up to but not including, so it won’t show ten. If I put ten here, run this.
Notice it only goes up to eight. So to include ten I need to be one over that. So if we put eleven, then that’s the only way we get to ten. Okay, so there’s another handy function to keep in mind. There’s also something known as zip. Let me show you what that looks like. A zip is used to zip two things together just like a zipper on your jacket. So let’s say we have my NUM list and that contains 12345, for example. And then we have words. Let’s say we have a list of words and I have five words here. Hello. My name is Mt. Oz. So that’s 12345 words. Now, if I wanted to zip these two things together, I could actually do that using the zip function. Let me show you what that looks like. If I invoke zip and pass in to the first argument of this, my numb, and then the second argument words and I can assign this to something. Let’s assign it to Combined Items object and you’ll know exactly what kind of object this is. In just a moment, let’s print Combined Items.
So let’s run this and notice this is a zipped object. But what good is this? This just shows where in the memory of the computer is this zipped object and what does it even mean? How could we use it? Well, let’s use it in the loop. So let me show you for item in Combined Items, I can print item and you’ll see exactly What That Looks Like. Make sure you use this print function properly. And there we go. Let’s run this and boom. Look at what that did. It zipped together both of these two lists. That’s exactly what the zip function does. And it saved that data into this combined items. And so this is basically a collection of tuples. Okay, each item in this combined items object is a tuple and it’s basically a zipping of the first item with the first item here, the second item with the second item in this list, the third item and the third item in this list and so on. Now, of course, I don’t have to assign this zipped function to anything. I could just use this directly instead of assigning it to combined items and then looping over those combined items. I could just use this directly in the loop.
So let’s take that and paste it right here. And it will work exactly the same way. All right, so let’s run this, and there we go. So this is a handy function. Now, this concept of having a number associated with an object, a number associated with an object, basically a counter associated with each object. One for hello, two for my, three for name and so on. These are strings, but it could be any other object type, right? We can have a list of anything. We can have a list of lists or list of tuples or list of any other objects. In this case, it’s a string. But the idea is that we’re combining this with an index counter 1234 and we’re putting it in a tuple. This is a very common practice, and you’re going to come across many examples as you become more experienced with python where you need to do something like this. This is known as enumeration.
Okay? And so there’s a built in function in Python known as Enumerate, which is really handy. So let me show you how you can use that. So we’ve got this words list which contains just the words What I could do is I can invoke the enumerate function. So let me get rid of this. I could say enumerate words. Now. What is this? Well, you’ll see let’s loop over it for item in enumerate words. Let’s print the item. Let’s run this and boom. There we go. Notice each item is a tuple and it has been enumerated. Each of the words have been assigned a number. So zero. Hello one my two name. Three is and so on. Now, enumerate actually starts with the 0th index position because it’s common practice, because in programming, first character or first item in a list or anything, it’s index position is always a zero. But if you wanted to start from the number one, you can actually you have something known as let’s put comma here, and you’ll see that you can put, for example, one.
And now it’s going to start at one. So let’s run this. And there we go. Notice it started at one and then 2345. So these are just some handy functions to keep in mind. You’ve got the zip, you’ve got the range function, the enumerate function. One thing about zip that I forgot to COVID let’s go back to that for a second. Let’s loop over the items in zipping. These two lists, my numb or my numbs rather. Let’s change that to plural because that makes more sense.
My numbs and then words. Now, let’s say if I print this, of course we’ve got five items here in the first list and five items in the second list, so everything pans out properly. But let’s say we’ve got a bunch of other items here in the top list. Let’s six, seven, eight, or eight, nine and so on. We’ve got many items in the first one and not as many in the second one. What happens in this situation? Well, it actually just maps out to the ones that it can and it ignores the rest. Okay, so it starts from the beginning to the point where both lists have the common size up to five. It’s going to ignore the rest of these numbers unless we have, of course, a bigger list on the bottom here. So let’s play this.
Notice it ignores numbers 6789 because we don’t have that many items in the second list. So it just maps out into that order sequentially and ignores the rest. And that’s how typically any zipper would work, right? Let’s say you’ve got a jacket with one long zipper side and the other side is not as long. You’re only going to zip to wherever they’re both able to be zipped. The rest of the jacket’s zipper lining is going to be sort of extended, right? Hopefully you get the picture.
- More Handy Functions and the Random Package
We spoke about the zip function, and I want to expand upon that a little bit and show you how you can actually unpack using zipped lists. Okay, we talked about zipping a list in the previous lesson, so let’s discuss that a bit further. So here I’ve got three lists. I’ve got list A, list B, and list C. If I want to zip them, like I showed you before, we could just use the zip function. But notice now we have three lists. So all you have to do is add all of these together. So you put a comma between that, so list B, and then finally list C, all being passed as an argument to the zip function. And now this is going to zip all these lists together. Now again, if I was to just print out what this is, it’s just going to give me an zipped object. Let’s run this. Notice it gives me an object in memory, which is no use to us. So let’s actually convert this object into a list. And again, we’re going to get more into what objects are, and you’re going to understand exactly what this means. Don’t worry about this complex looking piece of syntax here. We’ll get into that later and you’ll see it’s actually much easier than it looks. But anyway, we zip this. And now let’s turn this into a list.
Make sure you get the direction of the parentheses correctly. We’re zipping these three lists, and then we’re creating a list out of them. And so let’s save this into a zipped list variable. You can really call it anything you want, but it makes sense for it to be called a zipped list. Now, if I print this zipped list, it’s going to actually show a list of tuples. So let’s run this. And there we go. We’ve got each of the tuples with three values, and as you can see, it’s A-B-C one, two, three, in that exact order. Okay, now we talked about unpacking a couple of lectures ago, right? So you can actually unpack this zipped list. So if I do A for loop and say A-B-C it’s going to represent each of the items in the tuples within the list I could do in zipped list, and then I could actually print out each of those items. All right, so print A, print B, and then print C just like that. And you’ll be able to separate out, pick and choose the items you want and notice it prints it in the correct order in which it’s supposed to be printed. Okay, so this of course, is like list unpacking. We talked about that already.
More specifically, we’re actually unpacking each of the tuples, and the syntax would be exactly the same if I was to add these parentheses. It’s going to work exactly the same. It’s just easier to read that this is a tuple that we’re trying to unpack. And by default. Most of Python, you’ll see that when you have collections within collections by default, it typically relies on a tuple because tuples don’t change. So if you have collections within a collection, the inner collection is typically a tuple by default within the Python language. You’ll see that being used across the language a lot. Now what if we wanted to check whether something exists within a list? You use the in clause. So let me clear away some of this code. And let’s say we have list A here. If I do the following z in list A, if I actually do this test and print out whatever this is going to be, well, of course, this is actually a boolean. This result is going to be a boolean. This is a boolean check. We’re checking to see if this character z or this object Z string exists in this list A. And as you can see, we don’t have that.
So what is this going to return? Well, let’s run this and notice it’s going to return false. If I choose something that does exist, for example, A, it’s going to return true. And this works with numbers, it works with objects, it even works with dictionaries. So for example, if I have a dictionary, let’s create a dictionary. We’re going to say that this has names and weights. So let’s have a guy named John and his weight is £140. And so this is a dictionary. So I could actually check whether the number or the name John exists within this. So I could do John in this dictionary. And so the whatever this is going to return is going to be either a true or a false together, right? So let’s print this out. I’m going to print like that. And so let’s run this and notice it prints true because John does exist. Now you might wonder, what if we wish to check for numbers? Let’s see if we do 140. Does 140 exist in this dictionary? You’ll notice that it does not return true. It actually returns a false. Let’s run this. It returns false. The reason is because dictionaries are keys and values. There’s pairs of keys and values. By default, when you do a check like this, when you’re checking for something within a dictionary, by default, it checks only for the keys. Okay, so the key here is John, the value is 140.
So to actually check for whether this 140 exists in the values in this dictionary, you’d actually have to invoke the values function, which we’ve seen already, right? So you dot values. And now it’s only going to take into consideration the values in this dictionary. And there could be many values. In this case, we just have one key, one value. So 140 does exist in this expression here.
So let’s run this. And there we go. It’s true. Now we’ve got some handy math functions. So you can do a min max, for example. Let’s say we have a list B. We have a bunch of numbers in here, 12345 or whatever. You could actually do a max or min to find out what the biggest number is in a list or the smallest number in the list. All right, so obviously we can clearly see what the biggest and smallest number is. But when you’re coding, you may come across lists that’s being downloaded from the Internet, some data that you’re working with from files. And you want to check what’s the largest element within a file or the smallest element. You could do that using the Min max functions.
So if I do max on list B, this is going to return the value. Okay. And so let’s see what that is. Let’s save that in an answer variable and print what answer is going to be. So let’s run this and notice it gives five similar to this. We have a min function which works exactly the same way. Let’s run this. It gives me the minimum value that’s within that list. Now does this work with characters? Well, let’s see if it’s smart enough to do that. So let’s take list A and put that in here and see if it’s able to differentiate between the smallest character and the largest character.
So let’s run this. And so Min, here is a So far, so good. Let’s see if max, if it’s able to figure out whether F is the largest character in this. So let’s run this and notice it does. So it’s smart enough to differentiate between numbers as well as characters. It uses numerical order for numbers and alphabetical order for alphabets. Pretty cool. Now we’re going to get into some handy built in Python libraries that we can use to do various things. We’ll talk about that more later. But I just want to introduce to you something very handy. Let’s say you wanted a random number generated between a value, right? Let’s say from zero to 1000. You just want some random number between that, that is not biased, that is as close to unbiased as possible.
Well, you can use something called a randint function. And so if I use Rand int just like this and try to use it by saying, hey, I want to get a random number between zero and 10, if I run this the way it is, it’s actually going to complain. Let’s run this. Notice it’s giving me an error. It says what is randint? It’s not defined. The reason is that this is actually defined in a different module. It’s part of the Python library. We have to import that Python library in this file to be able to utilize that code. So the syntax for that, and we’re going to talk more about the syntax much later on. But I’m just introducing to you this functionality we could do from random. All right.
And notice you can see the icon here. It’s a python icon. So this is coming from the Python libraries. Import randint. All right? And as soon as you type in import and you put in some character, notice these are all the different types of functions or code that we have access to from the random library that’s part of Python. So here’s rand int right here. So now if I import that, notice this is no longer complaining. And this is going to return me a random integer between zero to 1000. So let’s save that into a random number variable, okay? And let’s print that random number variable. And let’s run this and whoops. I think I made a mistake. Yeah, I have a space here. Again, Python is very space sensitive. So unless you’re nesting and you’re inside of a block of code, everything should be outside, right? So that’s why it’s complaining. So let’s run this. And now notice it gives me a random number of 677. Now I can keep running this, and I’m going to get different random numbers because this rand int picks up random numbers. So let’s run this again. I get 880. Let’s run this again. I got 77. Let’s run that again. I get 19. Let’s run it again. So as you can see, it’s pretty random. Creating this kind of functionality on your own would be a lot more difficult to do, believe it or not.
So it’s great that the Python libraries comes built in with this. Now, let’s say you wanted to shuffle a bunch of data in a list. Let’s say it comes within a given order and you want to just shift all of that around. Well, what you could do is use this shuffle function, and I’m going to show you what that is. Let’s do that. I’m going to clear some of this code, and from the random library, I’m going to import shuffle. There you go. As soon as you type in sh, it gives you that IntelliSense there. And so from the random library, we’re bringing in shuffle. And now we can use this shuffle to shuffle things around. So let’s say if I have a list, let’s call it my list, and I give it a bunch of values, three, four, and then five. And then if I want to shuffle these values, I could actually just invoke the shuffle function and pass in my list. Okay. And now if I print the contents of my list, you’re going to notice that it’s no longer in this order. It’s going to be in a shuffled order. Let’s run this. And there you go. It’s 12543. Let’s run it again. It’s going to shuffle in a different way. 13254.
Let’s run it again. It’s shuffling in different ways. Okay, again, this is coming from random. So as an assignment, I’d like you to try this. I’d like you to shuffle numbers from zero to 100. And I don’t want you to fill up a list of one to 100 that’ll take you way too long, right? So don’t manually type up all the numbers. Use some of the knowledge that I’ve already provided you and create a list of 100 numbers and shuffle them around and print the contents. So try that out on your own and then you can resume to watch my solution. Okay, welcome back. Hopefully that wasn’t too difficult. So, first things first, we can use the range function, right? We talked about the range function and so if I have a range of 100 and I turn this into a list using the list function that we spoke about, and I save this into my list. For example, now all of a sudden, we now have this, my list that contains numbers from zero to well, you’ll see, it’ll actually be zero to 99 in this case. Let me get rid of this and let’s just print my list. And you’ll see it has numbers from zero all the way down to 99.
OK? And the assignment was 100, right? So you’re going to have to change this to 101 because this number that is in the range that gets passed in as an argument to the range function is non inclusive. So up to but not including this number. So we have to put 10 one and that’s how we get 100 numbers. So zero to 100, that’s going to be the contents of our list. Let’s run this and you’ll see that this is the entire list, including the number 100. Now we need to shuffle this. So how would we shuffle? Well, all I would have to do is invoke the shuffle function on my list like that, and when this line runs for the rest of the code that is to follow, the bigger and better code that is supposed to follow after that line will have the shuffled list. Okay, very important point to keep in mind. This shuffle function mutates or changes the list, the values, the order in which they’re stored it.
Shuffles that around, okay. And it shuffles that for the remainder of the program. So once this line runs, we’ve changed the order of the list and from here on, fourth, we’ll never have the same order of the list again. It’ll be based on what this function changed it to. Right? So let’s run this. And now notice the numbers are randomized, okay. And I can run this again, it’ll be randomized in a different way. Notice it’s now 61 as the first value and we got seven down here. Let’s run this again and you’ll notice it’ll, keep shuffling it in a different way every time we re execute the program because shuffle again is coming from the random package. Now, you might be wondering, if I print this list and I print it again, is it going to be shuffled in a different way? No, it’s not.
Okay, so let’s print this a couple of times and let’s just run this program once. Okay, let’s run this once. Boom. And notice that once this line of code was run, it shuffled the list in whatever order it wanted to. And so now the order that we see here is going to be consistent across the remainder of the program. Whatever lines of code we have later, as long as we refer to my list, my list is now changed to this particular order that the shuffle put it into. And so that’s why we have this random order and it’s being repeated. You’ll see that it’s consistent across every use of my list, okay? In one program execution. But if I rerun this program again, notice it’s going to be a completely different run. Shuffle is going to shuffle it in a different way, and then the bigger and better code will have different data within the list. Okay? So hopefully you get the idea.