Please Master These 10 Python Functions…

Please Master These 10 Python Functions…

Show Video

if you write any code in Python then you'll see these 10 python functions a ton and it's important you master them some of them may seem simple but they have a lot of additional parameters that you need to understand as they can save you a ton of time so with that said let's dive in and look at function number one so the first function we'll look at here is the print function now this is probably the first thing you learn When You Learn Python and it seems super basic we can print out a few different things we can separate them by commas and you can see that we can print a mix of strings and variables and when we do that they'll get printed out separated by a space but what you probably didn't know is that we can pass additional arguments to the print function then modify how it works for example I can pass this sep argument here so sep is equal to and I'll go with something like a pipe and now what will happen is rather than using a space as the delimiter or what goes in between the different arguments we passed to the print function we'll use this pipe so when I run the code now you see we get my name is and then pipe pipe and I am pipe 23 pipe years old so we can override that default Behavior which is to use a space to separate all the different things we're Printing and in this case we use a pipe now maybe instead we want to use a comma so let's go back here and change that to a comma and print this out and now you can see that we're printing things with a comma this is quite useful especially when you want to print out things that have a certain formatting and you don't want to do the manual formatting yourself now another thing we should know about the print function is how we change what gets printed at the end of the line line so you may not know this but by default when you print something with this function it's going to actually add a back sln which is a new line character which will force the terminal to go to the next line so when you print something else it won't be on the same line now typically this is what you want and that means when I run the code here you'll see we get these two print statements on separate lines but sometimes you actually want to print things on the same line so how do you do that well what we can actually do is we can override this end argument here and we can pass this something different than the new line character so I could pass say end is equal to a pipe and maybe put some spaces around it and if we clear here and run you'll see now we get hello world and at the end of this print statement it prints the pipe with the spaces and then when we go to print the next line it will happen on the same line here because we didn't move down to the next line so now we're going to dive into the second function here which is the help function but first I need to share with you something that's going to be very helpful and that is the sponsor of this video today's video is sponsored by mail trap an email delivery platform that developers Love Now what's cool about mail trap it's actionable analytics the best in the industry with full statistics and drill down reports on each and every email you sent mail trap offers separate streams for transactional and bulk emails SMTP and API Integrations Plus sdks for major Pro programming languages at mail trap human support is available round the clock for all customers try today at mail trap. so hopefully you appreciated that segue there but now let's have a look at the help function now the help function allows us to print out the documentation of a python function so we don't need to go to the internet to look it up and we can really quickly get access to how a function works now what this will do is read the dock strings of a function and simply give it to us so what I can do is something like help and then I can pass to this maybe the print function and notice I'm not calling the print function I'm just writing the name of it and now when I run the code you'll see that it actually prints out all of the documentation for the print function this is what's contained in the doc string for it so you can see it says print kind of shows you an example of how it works and then it gives you a description of the different arguments or the parameters for this function now this also works for your own functions so let me show you that so you can see here I've written a custom function called test Funk and I've just written a doc string for it just as an example so we can see how this works now when I run my code here notice it will actually give me the documentation of this function so it says a b and then the return type again it's really just printing out what the doc string is that's written here so this is useful for built-in functions but also when you're working with a library or code written by other people so you don't need to search through and find the actual function definition you can just use this help function it will print it out for you so the next function on my list is a very common one and you you've probably seen this especially if you're working with a for Loop and that is range now as much as range can be used to iterate through values in a for Loop we can also use it just to generate a list of numbers and I'll quickly walk through how it works because it is a very important function so what range will do is generate a range of numbers starting at some value stopping at some value and stepping by some value now by default when you only pass one value here to the range function this acts as the stop that means it's going to go up to but not include this number and it's going to start at one and step by one which means go up by one each time so if I run the code here you can see that this gives us the values 0 through 9 again because we go to the stopping point but we do not include it now if I have a second value here something like two and then 10 this will act as the start value and this will act as the stop value and now when I run this you see that we will simply start at two we will go up to 10 but not include it if I decide to add a third value here something like two this will act as the step value and this will be the increment that we will go up by each time so if I run this here we get 2 4 6 8 now this is quite useful and we can do this in many different kind of ways to generate a lot of different sequences of numbers for example I can change this to ative -2 and I can swap these values around and go maybe 10 and maybe we're actually going to go to something like -10 and now this will give us a negative range where we start at 10 and we subtract two each time until we hit the stopping value of -10 which we do not include very useful for for Loops but also if you convert this range into a list then you can simply use it as a list of values one thing to note if you print out range itself which we can do here you'll see that we actually get a range object that's because range returns to us something known as an iterator an iterator is something that we step through using kind of a specific process that I don't need to get into in this video the point is if you want to actually get an entire list of values you do need to manually convert this to a list okay so to do that we just write the list function around range and then as you saw before it gives us a list of values rather than this range object which again is an iterator now the next function we're looking at is the map function now a map function allows us to apply a function to every single item in an iterable object an iterable object is anything that you can Loop through so something like a string a list a tupple something like a set it works for all of those so let's have a look at a quick example so let's say that what we want to do is we want to get the length of all of the different strings in this list well we could iterate through every single one of these strings manually apply the length function and then just print it out or store it in a new list but instead we can actually use the map function that does all of this for us so I can say the lengths is equal to and then I can use my map function and the first thing I pass to the map function is the function that I want to apply to all of the different items in my iterable so in this case I passed the Len function we can pass our own function or in this case a built-in one in Python and then I pass the iterable that I want to apply this to which is strings now what I can do is I can print out and I need to convert this to a list because again this is going to return an iterator so it's going to return a map object if we want to see all of the results then we need to First convert it to a list and now if I run my code you see that it gives me the length of all of these different items so it simply took this function applied it to every single item that was in this list and then gave me that result inside of in this case a new list or really a new iterable that we converted to a list now in this case we used a built-in function in Python but we can also use a custom function that we write ourself now it's common here to use what's known as a Lambda function a Lambda function is a oneline a nymous function where you can do something like Lambda you can pass a parameter in this case it will be X and then if we want we could do something like x + S now what this is going to do is it's going to pass every single one of the strings to this function as the parameter X and we're simply going to add an S to all of these different strings so now what I'm going to do is write run this code sory and you can see we get an S tacked on to every single one of these strings now if you don't want to use a Lambda function you can Define your own function so we can say addore s we can take in our string okay and then we can say something like return and then string plus s and now we can just put the name of this function notice I'm not calling it I'm just putting it uh as the name and then when I run this you can see that we get the exact same result so that is map it is extremely useful again you pass the function you pass the iterable object and then it will apply this function to every single item and give you all of the results so now we're moving on to the next function which is the filter function which is closely related to the map function the way the filter function will work is it will take every single item in our iterable object it will pass it to some function in this case it's called the filter function and if that function returns true it will keep that item otherwise it will remove it from the result so let me show you an example we'll just say filter is equal to and then we're going to use filter same thing we're going to pass our function in this case I'm going to pass this custom function I wrote called longer than four which just returns true if the length of a string is greater than four and then I'm going to pass my iterable which is strings and we are going to print out the list of our filtered okay so let's spell that correctly and let's run our code and notice that we only get world and apple the reason for that is what really happens here is we take every single one of our items so we start with my we pass it to this function this function returns false because my is not a length greater than four we pass world we return true because this is length five same thing with apple length five pair is length four so it's not greater than length four so we don't include it so we end up with world and apple obviously this is a very simple function we can write very complex functions and this allows us to filter an iterable object based on some function which can be very very useful mess around with this and also remember that you can use the Lambda function as well so we could have written it like this Lambda X and then we could say Len X is greater than four and to prove that to you if we type this correctly and we run the code you see that we get the exact same result so the next function to look at here is a simple one and this is is the sum function the sum function is simply going to return the sum of all of the different numbers that you pass it from some kind of iterable object in this case we're passing an iterable which is a set we could pass a list we could pass a tuple doesn't matter so long as the values inside of the iterable are numbers if they are not numeric so not an INT or a float then you are going to get some kind of error so quickly we can run the code here and you can see that we get the sum of 35.5 now one thing you might not know about the sum function is that you can actually pass to this a start value so we can pass a start of say 10 and now we will start summing at 10 so now you'll see we get 45.5 now of course we can

make this a negative value as well so let's go ahead and do that and you can see that this works perfectly fine now the next function on my list is the sorted function now this is pretty straightforward this is going to sort an iterable object in ascending or descending order depending on what we tell it now in this case we just have a bunch of different numbers by default it's going to sort this in ascending order so if I run the code here you can see that we get these numbers sorted in ascending order now there are a few different arguments that I can pass to this sorted function to change its behavior for example I can pass reverse if we spell this correctly equal to true and then when I run my code here you can see that we actually get all of the values in reverse order but another more interesting argument we can pass here is a key now the key will actually be a python function and we will apply this python function to every single item inside of our iterable and we will s ort the items based on what's returned from the key function now I'm going to show you a better example of this so stay with me for one second okay so I just created a better example here so you can see how this works so I have a list of people and notice that if I try to sort this list of people we just have python dictionaries here and the sorted function isn't really going to know how to sort this it will do some kind of sort for us but it's going to be pretty unpredictable so instead what we do is we pass to this a key now this key is a Lambda function we take in one argument in this case it is person and in this case we get access to the person's age so what we're doing effectively here is we're sorting these people based on their age so now when I run the code here and we print this out you can see that we get all of the people sorted in ascending order based on their age because we're sorting all of the different items using this key now if we wanted to go a step further we could reverse this as well and now we could sort this in ascending or sorry descending order and you can see we can start with the oldest person and go to the youngest moving on the next function to show you is enumerate but in order to see the value of a numerate we first have to look at what happens when we don't use it so often times when we're iterating with a for Loop we want to have access to both the index and the value When We're looping through something like a list in this case you see that I create a simple for loop I say four index in range and then the length of tasks and then I use that index to access the task that's at that specific position I then print out index plus one and the task and this gives us kind of a nice list so if we run the code here you can see that we get a list of all of our various tasks now this is fine there's nothing wrong with this code we can clean it up quite a bit by using the enumerate function now this is helpful again when you want the index and the value iterating through some kind of iterable so what I'm going to do is change this here to use enumerate and I'm going to enumerate over tasks now when I do that the first value that I'm going to have access access to here sorry is the index and the next value will be the task so what en numerate will really do is it will return to me a tuple a tle for every single object where the first object inside of that tupple is the index and the second object is the value so now what I can do is I can clear this and I can run and you see we get the exact same thing so again first variable is going to be the index second value is going to be whatever the value actually is and we can use that for a numerate now it's also worth noting that we don't need to use a numerate just in a for Loop if we print out for example the list representation of a numerate you will see what we get and it is a tupple where we have the index first and then the value index value index value Etc so moving on the next function on my list is the zip function but in order to understand the value of using the zip function we first have to see what it looks like when we don't use it so in this case you can see we have two lists right we have names and we have ages now these have corresponding values so the name at position zero corresponds to the age position zero in the other list so what I'm doing here is I'm looping through both of these lists at the same time and then I'm printing out name is 8 years old I'm essentially combining these two values together and using them in some kind of expression now notice that what I had to do here with my range is I had to get the minimum length of the names and the ages list the reason why I had to look for the minimum is because if we have an extra age or an extra name then we'll get an index out of bounds exception when we try to access the corresponding position in the other list for example if we add another name like Tim here and we don't have a corresponding age when we looked for the age at that index if we were just looping through the length of names then we're going to get an error so I have to look at the minimum okay so when I run this code you can see that we get all of the different kind of printed out statements here Alice is 30 Bob is 25 Etc now this is fine again nothing wrong with this code but let me show you how much easier it is for us to actually execute this using the zip function so I'm going to paste this in here and you can see that now we're using the zip function now what the zip function will do is combine different iterable objects together and automatically handle when one iterable object has more objects than the other so in this case what's going to happen is it's going to combine our names and ages into actually a list of tupples and then this allows us to Loop through them really easily so let me just run this you can see how it works and then we can break it down more in depth so first let's print out what the zip actually looks like so I'm going to say print combined and you can see when I do that we actually get a bunch of different tuples right so we get the name then we get the age name age name age and notice it didn't include Tim because we didn't have a corresponding age now if we wanted to go a step further we could actually include another list so we could have maybe a gender and we have female male and then male and now notice if I add my gender in here and then we add gender here and we go and is gender when we print this out you'll see that we're only going to get three lines this time and that's because the minimum length of all of the different lists we had was three so it can combine as many different iterables as we want and automatically handle when we have a mismatch number of them so again we get Alice 30 female Bob 25 male Charlie 35 male and then we can print all of this out zip is super super useful I use it all the time and I'd highly recommend you use it in your code as well especially when you have corresponding values in multiple different iterable objects so now we move on to the final function on my list which is open now open can be used to open a file read to it write from it it has a lot of different usage and let me explain to you how to properly use it so first let's create a variable called file and we'll use the open function and the first argument we pass to open is the file name we want to open so I'm going to go with test.txt now the second option is going to be the file mode there's a lot of other options as well as you can see here and there is a lot of different modes now the most common modes you're going to need to know about are going to be R which stands for read W which stands for write and then a which stands for append again there's a lot of other options but these are the three main ones you want to know now for now we're going to go with W because we want to create a new file and when you use W mode this is going to override a file if it already exists and essentially clear everything that's inside of it so make sure you're careful when you use this so now we've opened our file what we can do is write to it so we can say file. write and when we write we can just write some string so something like hello world and if we want to move to the next line in the file we need to make sure we use a backline or a new line character sorry I can say hello world my name is Tim like that so now if I run my code you'll see that a new file is created and we have Hello World my name is Tim however it's very important that after we create this file and we write to it that we close it so we need to actually say file. close just to make sure that we don't have any memory leaks and we don't leave the file open in memory when we actually don't mean to do that now in this case everything's fine if we don't uh actually close it but we just want to make sure that we do close them and that's actually why I'm going to recommend that when you are working with files rather than manually opening and closing them like this you use the syntax which is the following now this is the wi syntax so you're going to say with open and then again we can go our test.txt put our mode as W and we can say as and then in this case file and then we can say file. write and whatever we want to write here okay that's great and now anything that's indented will happen inside of this context manager that's what this is referred to and as soon as we exit this so as soon as we finish our operations it's automatically going to handle closing the file for us so this is the best practice when it comes to working with files rather than opening and closing them yourself you always use a context manager which will ensure that the file is always closed po properly even if an error occurs inside of the kind of lines where you're trying to manipulate the file so just make sure you do that anyways we have the mode so we have w we have R now if we use R mode this allows us to actually read the contents of the file so to do that we can say file. read and if we read this

we will get all of the text inside of here so we can say print and then text so let's print that out and you can see Hello World my name is Tim gets printed and then if we want to we can also append to a file now appending to a file is not going to override it it's simply going to add to the end so if you want to keep adding to the end of a file rather than replacing the contents inside of it then you use the append mode now what we can do is say file. write new edition like that and if we run the code here and we open this up you can see that we have the new addition getting added and which just going to get added at the end of wherever the file was so in this case we didn't have a new line character so it just gets smooshed to this line if you wanted it to be on a new line then you would need to add the new line character like that now there are also combination modes so for example you can do something like WR mode right where you're reading and you're writing to the file you can have like ra mode I think that's probably a mode I'm not sure if that's actually a valid one reading and appending and there are all kinds of other modes that you can look up and you can even ask chat GPT to tell you it's just too many for me to cover in this video anyways with that said that is going to cover the 10 python functions that you need to master I hope you found this video helpful if you did make sure you leave a like subscribe to the channel and I will see you in the next one [Music]

2024-06-12 15:20

Show Video

Other news