10 Python Shortcuts You Need To Know

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello everybody and welcome back in this video i'm going to be showing you 10 python shortcuts that you need to know none of these shortcuts are advanced they are simply python language features that save you a few lines of code and a little bit of time these things may exist in other programming languages but most of them are specific to python and well if you write in python a fair amount this is definitely something worth watching and shortcuts worth remembering so with that said the first thing that you need to know is actually the sponsor of this video thanks to career karma for sponsoring this video career karma is a platform that helps connect learners like you to amazing boot camps and courses that prepare you for jobs in tech i've worked with career karma in the past and share their mission of inspiring motivating and helping others get started with their tech careers if you're looking to start your career in tech as a web developer data scientist ui ux designer whatever it may be then career karma can help you in your journey and get you into some great boot camps boot camps are the fastest way to quickly switch to a tech career that affords a six-figure salary work from home flexibility and high job satisfaction on the career karma app you can join live audio rooms and speak to people like me in fact i just did a live audio room the other day and it was a great experience to get started download the career karma app from the app store or click the link in the description where the first 1000 of my subscribers will get exclusive access to a free coaching session with the career karma coach thanks again to career karma for sponsoring this video alright so let's go ahead and dive in the first shortcut i have to show you is called f strings now f strings only work in python version 3.6 and above but they simply allow you to embed python expressions or variables inside of a string without having to use concatenation or string formatting or any other method you may use so for example let's say we have some variable and it is called name it is equal to tim let's say we then want to print out hello and then whatever the value of the name variable is to the screen well a few ways we could do this would be the following we could print something like hello comma name that would work we could print something like hello space plus name and that would work or we could use an f string which just makes things a lot easier and f string is simply a lowercase or uppercase f followed by a string either double quotes single quotes or triple quotes in either single or double quotation marks and then inside of the f string you can simply write any python expression or variable inside of curly braces and it will be evaluated as a string so if i print hello name like that let's just remove this we can see that this actually works we get hello tim now the great thing is when you have complicated strings that are using variables or expressions you can add stuff before and after the f string or sorry before and after the expression you can embed multiple expressions so i can do something like name times two and then i get hello tim tim i could even do some basic addition maybe two plus three like that i could write maybe a list inside of here right i could do something like one two three and then that gets displayed as a list there's a lot you can do with f strings again it's a lowercase or uppercase f only works in python version 3.6 or above and in my opinion is a shortcut to create a string now lastly you also could do something like x is equal to and then do that you don't have to be printing the f string and then i could obviously print this string so print x and you get the same thing all right that is shortcut number one let's move on to number two so moving on to shortcut number two i have for you unpacking now unpacking is extremely useful and essentially what this means or what this allows you to do is assign variables to all of the values inside of some type of collection in python so a collection in python could be something like a list like a dictionary like a string those are all examples of collections and what you can do is something like the following so see here inside of top standing for tuple i have five values one two three four five let's say i wanted to assign all of those values to variables well i could do something like a equals top at index zero and then b equals top at index one so on and so forth but that's pretty uh repetitive and i don't really want to write that so instead what i could do is a comma b comma c comma d comma e is equal to top and when i do that python knows to automatically assign a equal to 1 b equal to two c equal to three so on and so forth and to prove this to you i can just print them all out so if i do this you see we get one two three four five so you can do that with pretty much any collection i can also do this with my list so lst notice that works as well i could do this with my string so let's go ahead and do that i get hello well all spaced out hello i can do this with my dictionary so let's change this to just be a b and then dic okay a b like that notice this works notice when i do this with a dictionary it gives me the keys it does not give me the values if i wanted the values i would do or sorry items i would do dick dot actually not items dot values and then that's going to give me the values and if i did items you'll actually see what we get here we will get tuples so a1 b2 a is obviously the key 1 is the value b is the key 2 is the value so works with that and then a very common way or reason people use this is you have something like coordinates and you want to unpack them into x y so you can see i have my chords here 4 5 x y and then i go x comma y and well there you go i've unpacked this collection that's pretty much it for how unpacking works pretty simple but definitely very useful and saves you from having to write out a bunch of different variables on a bunch of different lines you can simply unpack the collection in this fashion one last thing to note is that if you have something like x y z equals chords you're gonna get an error because it cannot unpack there's not enough values here to unpack into these three variables all right let's move on to shortcut number three so i don't really have a proper name for this one but i'm going to call it multiple assignment or variable swap but essentially this shortcut allows you to assign multiple variables on the same line this is common in other programming languages but i figured i'd show it here in python so for example let's say i have a width and a height i can define them like this 400 500 so rather than having to write two lines width equals 400 and height equals 500 i can simply do it on one line so that's great but the more useful aspect of this feature is that i can actually swap the values of variables in one line as well so in other programming languages if you wanted to swap the value of width and height what you would have to do is something like this temp is equal to width width is equal to height and height is equal to temp because you need some way to store the value after you reassign this variable because once i assign width equal to height i lose the value for width and so i need to store it in this temporary variable so instead of having to do that in python what you can simply do is say width and then comma height is equal to height comma width and just to show you that i'm not lying here i can print the width and the height let's delete all of this and you should see that we get 500 400 because we have swapped the width and the height so that's it for this you can obviously do this with multiple values as well so even this inline swap i could say with comma height comma x and then i don't know maybe make this like 5 or something and well that still works all right so with that said let's move on to the next shortcut all right so moving on to one of the more useful and popular python shortcuts we have comprehensions now a comprehension is a way to initialize or create some type of collection in python in one line so let me just show you with a list first and then i'll show you with some other collections so here we have a list and i want to initialize this list with some values let's say i want to fill it with zeros maybe i want to fill it with a hundred zeros well i could write a for loop i could say 4i in range a hundred and then say x dot append zero but this is not the pythonic way to do this the pythonic way to do it is the following zero for i in range a hundred when you do this it is going to put whatever is on the left of the for statement inside of the list however many times this is running so in this case if i print out x now we see we get a list filled with a hundred zeros now of course i could use the value i here so i for i and range 100 now i get a list that goes up to 99 starting at zero and if i wanted to get even more advanced i could add an if statement here so i for i in range 100 if i mod 2 is equal to 0. now we're only going to get the even numbers plus 0 inside of here i could add another for loop so i could say 4 and j in range 10 and then maybe i do the product of i times j now if i do this obviously i get a large list but you can see where i'm going with this and how advanced you can really make this of course you can do a nested list comprehension as well i could do a list inside of here and say zero for underscore in range five for underscore in range five this will create a two-dimensional array for me so here you can see now we have an array or a list inside of a list if you're curious what the underscore is you can simply use an underscore instead of a variable name if you're not going to actually use the variable or iterator for your for loop and yeah that's pretty much how you use or do a list comprehension now of course you don't only have to do a list comprehension you could do this with a dictionary a tuple other data structures i'll quickly show you so what i'm actually going to do here is create something known as a generator you don't have to know what that is but that's why you'll see some weird output in a second so i'm going to say i 4i in and let's just go with hello and now notice i get a generator object don't worry about what that is but if i convert this to a list you can see that i get hello so this does work with tuples as well or sorry i could just convert this to a tuple and then i get that in a tuple nice okay uh other than that i could do this with a dictionary so a useful thing we can do with the dictionary is say count all of the characters in a word so let's say i have a word which is equal to hello my name is tim i understand this isn't a word but we can just change this to sentence what i can do now is something like char colon and then sentence dot count char or char in the set of the sentence this might seem a little bit complicated but i'm getting all of the unique letters from the sentence i'm looping through them and then for every single one of those letters i'm counting how many times they occur inside of the sentence not the most efficient way to do this but this will give me the frequency of these characters in the sentence so if i do this now you can see i am getting that from this dictionary comprehension all right i'm going to end it there you can do this with a few other collections as well let's move on to the next shortcut the next shortcut i have for you is a simple one this is object multiplication this simply allows you to multiply objects in python when i say objects i don't just mean numbers i mean strings lists etc so let me show you so a very popular thing to do is to multiply a string so let's say i have a string hello maybe i want to multiply this by 5. well you can guess what the result is going to be well we get hello five times so that's what i'm talking about here now of course you can multiply a list as well so one two three times five i get one two three five times in the same list we can multiply a nested list if we wanted to do that one two three and then we get the nested list inside of the larger list i could of course do this with a tuple as well so let's just go one two times five of course you can make this a larger number now if you try to do this with two tuples or something you'll see that a few things i just showed you list tuples and strings definitely are multipliable in python the next shortcut i have for you is very popular in most programming languages in javascript they have this in other programming languages they have this and this is the ternary or in line operator slash condition slash if statement so what i mean by this is the following in python you can do something like this x is equal to and then i could say maybe 1 if 2 is greater than 3 else 0 and if i print the value of x well you're going to see we get what we would expect here so you can put some type of condition you put what you want to occur or what you want to be assigned to the variable on the left hand side of the if statement and then what you want to happen if this is not the case after the else so whenever you do this you do need an else notice if i go like here and i don't add an else we get invalid syntax you must have an else pretty straightforward that's what it is now in javascript the parallel here would be this x is equal to uh two greater than three question mark one colon zero so you're putting the condition first then you're putting what occurs if this condition is true otherwise you are putting what happens otherwise right if this condition is false so pretty straightforward but this can be useful if you want to not have to actually write the entire if statement obviously if i wanted to write this out i would have to do something like if two is greater than three x equals one else colon x equals zero so you can see this saves you quite a few lines of code and just looks a bit cleaner and definitely has its place in python programs the next shortcut i have for you in python is the zip function so i'll write it out right here but it looks like this what this will do is combine lists or collections together so usually you can iterate through them at the same time now before i iterate through them i'll just show you exactly what this does and you'll see why it's useful i'm going to print the list of the zip of the names ages and i underscore color notice how tim corresponds with 21 and blue joe corresponds with 19 and brown so on and so forth all of these kind of correspond with each other at the corresponding indexes if i print this out notice that we get tuples that are combining all three of these things so tim 21 blue joe 19 brown so on and so forth that's what the zip function does now of course i can do this with less things just names and ages now if i run this we just get the name and the age i could of course do this with just the names and the eye color like that and then i just want to show you what happens if you have too many elements in one of your lists so here let's just say i add an extra element so this has four this has four this has five now i'm trying to zip something that has four elements and five elements watch what happens nothing no error it simply skips or doesn't consider this last element or extra element in this eye color list so why is this useful well a lot of times you want to loop through the zip of lists so rather than looping through them and using the index to access the elements what you can do is set is something like this so for let's go name age in zip names ages and then i could simply do something like if the age is greater than 20 print the name and then i get tim and i get sally printing out so that's kind of where this would become useful of course i could add in the eye color as well i would just need to add i underscore color let's change that to colors and then i could just print the i underscore color no matter what so there you go that is zip pretty useful and yeah definitely just cleans up the program a little bit so the next shortcut i have for you is a little bit more advanced but this is star args and star star quarks now arg stands for arguments positional arguments specifically and quarks stands for key word arguments now positional argument is one in which position matters so if you look at this arg1 arg2 arg3 when i call this function the first value i pass in will be arg1 the second arg2 the third arg3 hence they are positional the position in which i pass the arguments matters whereas if you look at this function right here these are keyword arguments which means i could call this function like this func two arg2 equals x whatever i could do arg1 equals that i don't even need to pass these arguments and i can pass them in any order that i want whereas up here i need to pass all of them and i need to pass them in a specific order so what is star args and star star quarks well let's say i have a list that has all of the arguments i want to pass to a function or some collection maybe a tuple maybe a string that has all the stuff i want to pass to a function well the way that i can do this is something like this right i could go func one and then i could say args at index zero and then args at index one or i could decompose this right or break this down unpack it and have you know abc equals args then pass abc right here but there is a much faster way to do this what i can actually do is write star args now what star args will do is unpack this and split this into all of the three individual items so you can kind of imagine that star args removes this list right here and passes the values one two three like that as positional arguments to this function so when i go star args you will see here that i get one two three printing out now obviously let's just change this two two three it shows two two three now one of the best ways to visualize star args is to do the following if i print args notice we get a list if i print star args notice i get 2 2 3. the reason for that is all three of these values are passed as arguments to the print function so i print two then i print to then i print three so it would look like two two three inside of here when you do star arcs hopefully that's clear but that's what you can do with positional arguments great now when you have keyword arguments it's a little bit different so notice what happens here if i pass to func 2 quarks okay so we're looking at funct2 and we're looking at our keyword arguments right here if i do one asterisk and i pass quarks notice i'm printing out arg2 arg1 and arg3 the reason for that is i am actually passing these as positional arguments and specifically i am passing the keys in my dictionary as positional arguments to this function so arg one is actually equal to the string arg2 arg2 is equal to the string arg1 you can read the output and you can see what they're equal to that's because we're just passing the keys as positional arguments however if i do two asterisks this will actually pass the key as the argument name and or parameter name whatever you want to call it and then the value as the value for that argument or parameter so in this case we'll pass arg2 equals two our one equals one and we should get things printing out in the correct order now because we're passing the correct keyword arguments so to break this down for you as well what this would look like is arg2 is equal to two arg one is equal to one and then arg3 is equal to three that's what it looks like when you do star star quarkx like that all right so a little bit more advanced that's where i'll leave it though also note that you can do something like star args and let's go here star star wargs in the parameters but i'm not going to show that in this video so the next shortcut i have for you is one that many people do not know about and this is the four else or while else statement now what this allows you to do is determine if you broke out of a for loop or a while loop without having to use a flag so let me show you a classic example here let's say we have some target value let's say this target is equal to seven let's say we have some search array or search list and let's just give it some numbers okay one two three four five six and seven what you'll do often times is you'll look through this search list and you'll try to determine obviously we need an equal sign here if the target value is in the search data structure so in this case i would do something like for element in search and then i would check if the element is equal to the target the element is equal to the target i found what i'm looking for so i can break and then maybe i would print something like i found it exclamation point okay now the thing is i don't know if i got out of this for loop because i broke out of it or because i ran out of elements to look through so what a lot of people do is something like this they will say found is equal to false and then they can say found is equal to true and now outside of here i can check if found and i can maybe do something like if not found print i didn't find it exclamation point okay so that's what people usually do however there is a way to actually make this faster shortcut right what i can do instead is i can simply place an else statement here now what the else statement will do is it will be triggered if we get through the entire for loop without breaking so in this situation if i get rid of found here and i run this notice we get i found it because well we found it the else was not triggered we broke out of the for loop however if i make this target now eight and i run this we get i didn't find it because i didn't break out of the for loop there you go that's as simple as it is the else triggers if you don't break out otherwise it doesn't trigger if you break out you just escape it okay now you can do the same thing with a while loop so i will say well that's not going to work we could say well i is less than the len of search i is equal to 0. obviously a for loop is better for this purpose and i could say element is equal to search at i and while the same thing is going to work assuming i increment i uh oops i plus equals one i forgot what programming language we're writing in here for a second okay i didn't find it so same thing works with a four and a while loop that is all i want to show you the four else and while elsa statement all right so the next shortcut i have to show you is called sort by key and it is going to be relatable for you if you are trying to sort something that is relatively advanced or your search sorting criteria sorry is not default like you're not sorting in ascending or descending order what you're sorting by is something unique that the built-in python function just doesn't do so let me show you if i were to sort this list so lst.sort this will sort the list in place and i print lst what do you think is going to sort it by well it sorts it by the first element inside of the nested list that makes sense that's intuitive so we get negative one one two three four and four however what if i want to sort by the second element in the list well there's not really a way to do that i mean i could sort this in reverse i could say reversed equals true and now if i do this reverse equals true maybe it gives it to me in the reverse order however again i want to sort by this second element so i could write my own custom function that sorts this but instead there's actually a way you can do this using the built-in sort method what you do is you pass an argument to this called key now key tells you what it should sort each element inside of the list by so every element inside the list is one of these nested lists so what you need to do here is pass a function that returns what it should sort by for each element so in this case i'm going to say key equals lambda x colon x1 now what is lambda lambda is a one-line anonymous function not really going to explain it too much but essentially x is our parameter for this function and what i'm returning is x1 x1 is going to give me the second element inside of the nested list so if i do this now it's going to sort by the second key or sorry second element so we get 2 2 3 3 4 5. there you go that's as easy as it is now you can make this more advanced if you want i could sort it by x1 plus x0 and now we'll sort it by the sum of the the values in this list so if i do this here we get this is the lowest then three then five then six then seven and then nine makes sense now in case the lambda is confusing any of you it's the exact same as doing this so i can define say sort underscore function this is going to take in x and i'm going to return x0 plus x1 now instead of passing the lambda what i would do is pass the sort underscore function it's going to then return x0 plus x1 and then it will sort based on this key that we've put here so this will give us the exact same thing hopefully that makes sense but a useful feature this works not only inside of the dot sort it works inside of the sorted as well i can pass lst and then key equals and anything that sorts in python you can usually pass this key parameter all right so that was all of the shortcuts that i wanted to show you but if you stuck around until this point i'm going to give you a bonus shortcut this is called eatertools now itotools is a very cool module in python that allows you to do iteration related operations and can save you a ton of time a lot of stuff you normally do manually you can probably just take right from inner tools i'm just going to give you a few very short examples here of what eater tools can do and then of course you can look up the documentation on your own so first there's this function from either tools called accumulate what this will do is accumulate the sums of the values in order or in sequence from this list i probably misdescribed that we just have a look at what we get here when i do this notice i get the sum of the first element which is one then the sum of the first and the second element which is three then the sum of the first three elements which is six then the first four which is ten and then finally fifteen that is accumulate from iter tools the next thing i'm gonna show you is called chain so let's have a look at this pretty straightforward but what chain will do is combine the two lists that you have into one list without actually creating a new list such that you can iterate through it so all of these iter tools related stuff they usually return to an iterator now if you're not familiar with the difference between an iterator and a data structure an iterator is something that allows you to iterate through something it doesn't necessarily create a data structure so in this case when i chain two lists together i'm chaining list one and list two this returns an iterator that i can loop through that doesn't necessarily create a new data structure that has list and list two together the reason that's important is because if you were to create that data structure using up more memory in your program more space in ram so rather than actually creating it which you and i would usually do if we want to loop through both of these and have them kind of combined together you can just use dot chain and well it just works hopefully that was a decent explanation but let me run this and show you so when i chain this i get 1 2 3 4 5 a b c d now in this case since i converted this iterator to a list it did create a list but you could loop through this in a for loop and it wouldn't actually create the data structure for you it would use the two existing data structures and loop through them in the correct order okay that is uh the chain now the last one i will show you here is called compress what compress will do is it will only give you the values that correspond with a true condition in another list a little bit confusing but look here i'm compressing names and show names is a list of names strings show is some boolean values so one is true zero is false okay if this in this case here when i run this and you look at this i get tim bill gen notice tim corresponds with one bill corresponds with one gen corresponds with one it doesn't give me joe and it doesn't give me susan because here we have zero so that's a false right this is imagine these are just true and false that's what compressed does again doesn't necessarily create the data structure for you allows you to iterate through it but since we're converting it to a list so we can see what it's actually returning in this case it does create the structure all right i don't want to get into those in too much detail just wanted to introduce this to you in case any of you have not seen it i may actually be making a tutorial on it in the future but with that said i'm going to end the video here i tried to go pretty fast so that i didn't waste any of your time if you guys enjoyed the video make sure to leave a like subscribe to the channel i will see you in another one [Music]
Info
Channel: Tech With Tim
Views: 88,377
Rating: 4.9584656 out of 5
Keywords: tech with tim, shortcuts, python shortcuts, f strings, unpacking, multiple assignment, comprehensions, object multiplication, ternary conditions, zip function, args, kwargs, for and while else, sort by key, python coding, f strings python, un packing python, shortcut, python shortcut, shortcut programming, time, 10 shortcuts, bonus, career karma, keys, shortcut walkthrough, python shortcuts and tricks, basic shortcuts, shortcuts for beginners, python shortcuts for begginers
Id: CssrFJGH_dU
Channel Id: undefined
Length: 27min 27sec (1647 seconds)
Published: Fri Jul 30 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.