20 Everyday Tips & Tricks in Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this video was brought to you by IND dentle IO learning python Made Simple how's it going everyone in today's video we're going to be covering 20 tips and tricks that you can use in everyday python starting with the first trick which is a oneliner for swapping variables so suppose you have two variables one that contains text as a string and one that contains the integer value of 100 and suppose for whatever reason we want to assign B to A and A to B well in Python then it's pretty simple all we need to do is type in a is equal to b a so B will be assigned to a and a will be assigned to B and just to make this more beautiful I'm going to print before and after and when we run this what you should see is that before it was text 100 and after it's 100 text because a contains 100 and B contains text now and this is not limited to two you can even do it with three things so we can also add something as more text or we'll just say Bob now we can say ab and C is going to equal CBA and it's going to work the exact same way moving on to trick number two reversing iterables suppose you have two iterables one which will be a list of integer and one which is just a simple string in Python if you ever want to reverse an ital you can either use the Reversed method and flatten it or you can type in your it name and use the syntax of colon colon minus one and that will reverse everything inside of it and we can do the same thing for greeting so that when we run this you'll see that we will get the reverse of both of them tip number three string multiplication in this example I'm going to have a variable called chout of type string and it's going to contain ah but anyway typing out all these A's by hand can be quite annoying especially if you want to be specific so something else we can do is create something called shout 2 type string and here what we're going to do instead is Type in a * 20 you can multiply strings in Python which is really cool and at the end we're going to add H so this time we're actually controlling how many A's we have in our shout which means that when we print shout 2 what we should get as an output is this string over here with 20 a but of course you can also just print let's say Bob time 2 and you'll get Bob Bob as an output because it works with any string tip number four oneline conditions imagine you have a number and you want to check whether this number is odd or even well in general you can create a simple if else check but let's try to put that all on one line so here we'll type in result of type string is going to equal even if the condition is true which is if the number modulus operator I said modulus Operator 2 is equal to Z else it's going to be odd and this is all it took to check whether it was odd or even so now we can just print that result and we will find out whether 10 is odd or even and you don't even have to assign this to a result you can literally just place it directly in your print statement and it will work the exact same way tip number five concatenating strings or joining strings and for this example we're going to have a big variable called emails which contains three emails and what we want to do is combine these emails into a nicely formatted string because right now if we were to print this we can say print the FST string of emails and we can place in those emails but when we return this we're going to get this list object back which isn't really nice for the users so what we can do instead is use some quotation marks use a space and a comma and type in join and this will insert this string in between all of them so now we can type in we want to join these emails and before we run this I'll just switch this around but now if we were to run this you'll see that we will have it nicely formatted we'll have a comma a comma and then the end and this can be literally any string you want you can even add three dashes and they will go between these strings do join just makes it easy to combine elements from an ital together up next we have tip number six and for this example I'm going to be using a dictionary of type string to string which means we have a string key and a string value for each element and when you are working with dictionaries it's quite common that you're going to try to access something that doesn't exist maybe ABC but obviously that raises a key error so what's a good way to get around this if you don't want to raise an exception well something different that we can actually do is use dot notation and use the get method for the key that we're going to specify so here if we want to get the age for example what we're going to get as a return instead is none because age does not exist in our dictionary and that's exactly what get does it tries to get the value and if it doesn't exist it returns none and alternatively you can even add a default value directly after the value that you're trying to get so this will the default value and I'm just going to call it default which means if it cannot find age inside the dictionary it's going to return default or whatever you decide to put inside here that can even be an integer if you want you can add 999 or minus1 or whatever you want to return as a default otherwise if you entame you will get the name back tip number six set default a very powerful method we have with dictionaries which is very similar to G yet so for this example we're going to have some scores which is a dictionary of of type string to integer and Bob is obviously winning but what we want to do next is create a variable called Bob's score of type integer and we want to try to get the score from Bob so we'll type in scores do get or not this time this time we're going to type in set default and here we're going to type in Bob and in case Bob doesn't exist we're going to set the default to zero which means that if this user does not exist this dictionary is going to have a new value called Bob with the default set to zero so the next time we can actually keep track of that user and you will type in Bob score but obviously since Bob exists already we're going to get Bob's score back but what we can do now is copy and paste this below and change Bob score to James score and we're going to try to grab the value for James and then we can print Jam score and at the bottom we're going to print all of the scores and what you should notice is that when we try to run this Jam score is going to return zero by default because James does not exist in the dictionary and in addition to returning zero it also created a new entry in our dictionary with James who has a score of zero so from this point forward we can actually keep track of whatever score James might get tip number eight counters in programming there are going to be moments that you're going to want to keep track of how many elements exist in a certain iterable and we have two options at this point we can either create our own custom functionality to try to find out how many elements exist in an ital or we can go for the easy approach which is importing the counter from Collections and for demonstration purposes I'm going to create a list called letters which is going to contain a bunch of reoccurring letters then right below that I'm going to create a counter of type counter and all I'm going to do is wrap the letters in this counter and what that means is that we can get a bunch of Statistics back from this counter such as if we were to print the counter. total this will count how many elements are inside this list in total so here we have eight letters but something even more useful is the most common method because this will return which one of these are the most common and at this point we have three A's two B's and two C's so the counter object just makes it much easier to count what elements are inside our intervals and optional you can also specify how many you want to get back for the most common here we can say only to return the top three and that's exactly what it will do tip number nine enumerate by this point if you've been programming in Python you probably already know what enumerate does it allows you to enumerate any iterable so here we can type in for I and letter in enumerate letters we will print the enumeration and the letter so what that should give us back are the letters enumerated starting at zero if you want this to start at one you have the option to add one to I and the enumeration will start at one but something that's nicer that a lot of devs don't know about is that you can directly set a start and you can set that to one so the enumeration will begin with one and you'll get the exact same output and the benefit to this approach is that you can enter any number you want without having to do any Crazy M math so if you want to start this at - 1000 that's fine you can do that and it will start from - 1000 up next we have trick number 10 dictionary merging so to get started with this example I'm going to create two dictionaries of string to integer and here we have A1 B2 and for B we have C3 and D4 and what we want to do is combine both of these dictionaries well the easiest way to do it is to type in a pipeline B and that's going to combine both of the dictionaries into a new one otherwise if you just want to update one dictionary you can type in a pipeline equals B so you can actually perform that in place operation and the next time you print a you're going to get the exact same output tip number 11 underscore formatting if you ever have some sort of big number not bug number but big number you probably have encountered the problem of trying to keep track of the zeros here I wanted to create the number of 1 million but obviously I messed up because I'm blind and I have a hard time tracking how many zeros are here so one thing you can do in Python is place an underscore as a thousand separator or it doesn't have to be a thousand separator because you can place it anywhere you want so depending on the country you live in you can place the underscore anywhere you want these will be ignored by python as soon as you run your program as you can see if we were to print the big number we would get no underscores in the output this is only to help us as developers keep track of what we're doing so we don't make that silly mistake but there's something else we can do so pretend we have another big number and here we're just going to hardcode it but you might have gotten this value from somewhere else and you want to be able to read this much more easily in the console well what we can do is print the F string of this big number and use colon underscore and this will place the underscore between the thousands so that when we run this we will see exactly what this number is without having to use a pair of glasses or a microscope which just makes it much more convenient and of course you can also do this with a comma but unfortunately those are the only two separators that we have in Python when it comes to FST string formatting up next we have tip number 12 and for this example I'm going to create a class called multiplier and in the initializer we're just going to grab a value and assign it to the instance and the only reason we're doing this is because I want to show you that you can make a class directly callable and to do so all you need to use is the call Dunder method and here instead of Aug and keyword arguments we're going to replace that with other value of type integer and this will return an integer then we can return self. value times other value and what's cool about this is that we can create a sort of currying with our classes which means that we can type in something such as double of type multiplier and that will equal a multiplier of Two And if we ever want to call that all we need to do is type in double with the number that we want to multiply because the class is now directly callable as soon as we instantiate it and when we run it you'll see we will get back 20 as an output but you're not required to do all of this you can also just type in multiplier directly as an instance and add another pair of parentheses after that because once again this sets up the class and this actually calls it although I wouldn't recommend this approach cuz it looks quite confusing I would definitely recommend you set it up in a way that's much more readable such as creating an instance called double but otherwise wise it works exactly the same way tip number 13 method chaining for this example I'm going to create a class called person and this person is going to take a name and an age and it's also going to contain two methods that directly modify the instance so the first one is going to be called modify name which takes a new name and returns self so all we're going to do here that's different than usual is return self and I'll show you why we're going to do this in just a moment and right below that we're going to have one that's called modify age which will also return self but now that we have these two crazy methods that return self we can move on to the actual demonstration of what this does so at the bottom I'm going to create a variable called Bob of type person and that's going to equal a person who's obviously named Jeff I'm joking it's going to be Bob with the age of 29 and now with Bob we can actually modify that information using those methods so we can modify the age which we can set to 10 for whatever reason Bob is now younger and we can chain this with another method such as modify name and this can be set to Bob or it's already Bob I'm kind of crazy today so we'll set it to James but as you can see we can chain these methods indefinitely and now the next time we print out the FST string of bob. name and bob. H we should get the new values such as James and 10 moving on to tip number 14 which is just a trick I like to use all the time when I'm printing elements from an iterable to the console so in this example we're going to have a list of type string called foods and what I want to do is print all of these foods to the console but what I'm going to do is first unpack them so that I can use the special arguments that come with the print statement such as the separator between each element I'm going to want to use a comma and a space and at the end of this I want to add a full stop the default of end is a new line so I'd recommend you use that as well in addition to using the full stop so that the next time you print it will start on a new line but now when we run this you'll see that our elements will be printed to the console in a nice format but of course you can change this to whatever you want you can also add a dash in between and it will look like this tip number 15 representation at this point if you've ever worked with a class you'll know how annoying it is to actually print the instance of any class and you might be asking what am I talking about why is it annoying well let's create an instance of this person and print this person what you'll notice in the console is that we will get this very useful output regarding that person that it's a person at this memory address and I hope you can hear the sarcasm in my voice because this tells us literally nothing other than this is just a person object now unless you're a robot this information isn't that useful so something else we can do instead which can be very useful for a developer is to add the dunder representation method and this will return a string and you can literally return whatever string you want but I would recommend you return something that's readable to to the developer so by returning this kind of string we're telling the developer that it's still a person object but that it contains this information so that the next time we actually print this person object we get some useful information back something that we can actually understand tip number 16 a quick way to grab the first element and the last element of any iterable for this example we're going to have a list of people which will contain the strings of Bob James George Fred Luigi and Sophia so what we're going to do is first type in first and then I'm going to use an asterisk and an underscore and then type in last and that's going to equal the people now what this does is First grab the first element and then by adding an asterisk and a variable name we are unpacking everything in the middle this doesn't have to be an underscore underscore is just the convention for throwaway values this can also be middle if you want but we're going to leave it at underscore and then finally we're going to get the last person and with that being done we can type in first and last and what you should notice in the console is that we will get back both Bob and Sophia the only thing to note with this approach is that you should have at least two elements for this to actually work and in case you're curious about what's inside the middle you can also print underscore and what you'll notice is that it contains the rest of the elements it literally absorbed them so that we could grab the first and last element from our list moving on to tip number 17 which is my favorite debugging trick of all time so for this example we're going to have a name and an age and for whatever reason we're going to want to print these variables to the console with their variable names so here we can add the FST string add some curly braces and we're going to type in name equals and we're going to do the same thing for age and what you're going to notice is that we're going to get both the variable name and the actual value or result of this expression and this is really cool because you can literally put whatever you want inside here you can also add the length of let's say name or you can do 1 + 2 and it's going to evaluate it there with the actual expression so it's just a very cool quick way to debug your code tip number 18 rounding sometimes in your programs you're going to have some very weird numbers with some very weird decimals and depending on what you're doing you're not always going to care about Precision because it will hurt readability such as if someone is 12 years old you wouldn't really care for the rest of that information that shows that they are 12 point blah blah blah years old but anyway let's move on to to the round method which allows us to round a number to any amount of decimal places for example we can round it to two decimal places and we will get our number rounded to these two decimal places if you decide to exclude the Precision it's going to convert it into an integer otherwise what's very interesting about the round method is that you can also go backwards so you can actually start rounding the whole number so by providing minus one you'll see that it's going to round it to the 10 otherwise with minus 3 it's going to round it to the nearest 1,000 so I just thought it was really cool that you can also go backwards with rounding tip number 19 string replacement so here we're going to have a sentence that reads as the tired Red Fox on the red Farm ate a bored red pig and what we want to do is print the sentence do replace red with XXX just to show you where it was replaced and if we were to run this you'll notice that it replaced every single occurrence of red even if it was inside tired or inside bored and I did that intentionally to show you how you can easily get around that well in any case if we were to duplicate this a very easy way to get around this is to add a space in front of the variable or not the variable but the string you're actually searching for and of course you need need to replace it with something such as blue but that should also contain a space so the next time you actually replace that string you'll get the correct translation the tired Blue Fox on the blue Farm ate a bored blue Pig otherwise if we were to leave that space in you'll see that this sentence will not make any sense at all the tiblue Blue Fox on the blue Farm ate a bob blue blue Pig and it's cool because there's Bob and finally we have the last tip of of the day which is being able to provide a key for Max and Min in Python and to demonstrate that I'm going to import this list of string which will contain all of these names and I might actually just break this so you can see all of them but it will contain Timothy Bob James zebra Amanda Anna and Luigi and right now if we were to print the max of names or the Min of names we should get back the default implementation which will return the Max and the Min of the asky values so here we'll get zebra as the Max and Amanda as the Min but what if we have a different implementation that we want to use to calculate the Max and the Min for example what if I want to say that the max is whatever name contains the most a and the minan is the opposite of that well just to show you right now where we're standing with the names I'm going to create this for Loop which first will print the name and the name. lower. count of a so we can see how many A's each name contains so next if we were to run this we'll see that Bob and Timothy contain zero while James and zebra contains one and Amanda contains three and then Anna and Luigi 2 and zero so what we want is Amanda to come back as the max value well let's define a key that does just that so here we're going to print the max of names and we're going to define the key which is going to equal this Lambda expression Lambda x x. lower do count of a so this is going to return an integer which is going to be used to calculate the max because it's going to use this comparison now if we were to run this what we should get at the bottom is aanda and to make this more obvious that that's the max we will add the string of Max so as you can see Max is aanda otherwise if we were to change this to the Min we're going to get Timothy because that was the first value that contains zero it's not going to do this alphabetically any anymore it's just going to grab the first value that it found which contains zero since both Bob Timothy and Luigi contain zero but let's change this back to Max because I realized I also forgot to change this to minimum when running the program because something else you can do is also compare them by the length just by entering the length method and this is without the parenthesis because it's going to call this on every single element and return the one that has the longest length so now if we were to run this we would get Timothy because Timothy has the longest length and we can actually change this to length so we can see the length of all the names to verify that so here we get the length of all the names Bob has the shortest name and Timothy has the longest which means obviously if we were to duplicate this type in Min and change this to Min as well we should get Bob as an output all I wanted to mention is that we can Define our own custom key in case you want some sort of custom implementation for both both the Max and Min methods so yeah those were 20 tips and tricks that you can use in everyday python do let me know in the comment section down below what you thought about these whether you have some tips and tricks that you'd like to share but otherwise as always thanks for watching and I'll see you in the next video
Info
Channel: Indently
Views: 16,841
Rating: undefined out of 5
Keywords: pyton, pyhton, pythn
Id: YzUBJfGAFyA
Channel Id: undefined
Length: 25min 17sec (1517 seconds)
Published: Fri Jun 28 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.