Top 10 useful python shortcuts you should to know


In this topic, 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.

F Strings

All right, 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. 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 is makes things a lot easier. And F string is simply a lowercase or uppercase F followed by a string, either double quotes, single quotes for 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 us remove this. We can see that this actually works.

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 at Tim, Tim. I 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 1, 2, 3, and then that gets displayed as a list. There’s a lot. You can do that 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 I’m packing is extremely useful and essentially what this means, or what this allows you to do is assigned 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 well, what you can do is something like the following. So see here inside of top, standing for Topal, I have five valleys, 1, 2, 3, 4, 5, let’s say I want to assign all of those values to variables. Well, I could do something like a equals top at index zero and then V equals top at index one. So on and so forth, but that’s pretty re 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 one 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 1, 2, 3, 4, 5. 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, wont all spaced out.

Hello. I can do this with my dictionary. So let’s change this to just be a B, and then D I C 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 a DIC 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 topples. So a one B2 a is obviously the key. Uh, one is the value. B is the key two is the valley.

So it works with that. And then a very common way or reason people use this is you have something like coordinates and you want to, uh, unpack them into X, Y so you can see, I have my cords here, four for five X, Y, and then I can 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 XYZ equals chords, you’re going to get an error. It cannot unpack. There’s not enough values here to unpack into these three variables.

Multiple Assignment

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 Simons or a 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 height. I can define them like this 400, 500. So rather than having to write two lines with 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 want it to swap the value of width and height, while you would have to do with something like this, temp is equal to width with is equal to height and height is equal to temp because you S you need some way to store the value after you reassign this variable. Cause once I assigned with 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 swamped 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 can say with comma height, comma X, and then I don’t know, maybe make this like five or something. And well, that still works. All right. So with that said, let’s move on to the next shortcut. All right.

  How to create a website using python as fast as possible


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 four loop. I could say for I in range a hundred and then say X dot append zero.

But this is not the PI phonic way to do this. The Python way to do it is the following zero four. I in range a hundred. When you do this, it is going to put whatever is on the left of the four statement side of the list. How 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 zeroes. Now, of course I could use the value I hear. So I for I and range a hundred. Now I get a list that goes up to 99, starting at zero. And if I want to do get even more advanced, I could add an if statement here. So I four I and range a hundred. If I mod two is equal to zero.

Now we’re only going to get the even numbers. Plus zero inside of here. I could add another for-loop. So I can say for 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. You can see where I’m going with this and how advanced you can really make this. Of course, you can do a nested this comprehension as well. I could do it list inside of here and say zero four, underscore in range, five, four, underscore in ranch, five. This will create a two dimensional array for me.

So here you can see, now we have an array or 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’d use or do a list comprehension. Now, of course, you don’t only have to do a list comprehension. You can do this with a dictionary, a couple 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 gonna say I for I 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 tumbles as well, or sorry. I could just convert this to a topple and then I get that in a topos. Nice. Okay. Uh, other than that, I could do this with a dictionary. So I useful thing we can do with the dictionary is say count all of the characters in a word. So let’s say, have a word which is equal to hello. My name is Tim. 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 for 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, but let’s move on to the next shortcut.

Object Multiplication

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, et cetera. So let me show you. So a very popular thing to do is do multiply a string. So let’s say I have a string. Hello? Maybe I want to multiply this by five. Well, you can guess what the result is going to be. Will 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 1, 2, 3 times five, I get 1, 2, 3, 5 times in the same list. Uh, we can multiply a nested list if we want us to do that 1, 2, 3, and then we get the nested list inside of the larger list. I could of course do this with a tumble 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 topples or something, you’ll see that a few things I just showed you list tumbles and strings definitely are multipliable in Python.

Ternary Conditions

The next shortcut I have view is very popular. In most programming in JavaScript, they have this and other programming languages. They have this, and this is the turnery or in line operator slash conditioned 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 one, if two is greater than three L’s zero. And if I print the value of X, while 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 F statement, and then what you want to happen if this is not the case after the ELLs. So whenever you do this, you do need an else.

Notice if I go like here and I don’t add an Ellis, we get invalid syntax. You must have an ELs pretty straight forward. That’s what it is now in JavaScript. The parallel here would be this X is equal to 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, uh, what happens otherwise, right? If this condition is false. So pretty sure four, but this can be useful if you want to not have to actually write the entire 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.

  Top 5 python modules that are great for beginners

Zip Function

The next shortcut I have for you in Python is the zip function. So I will 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, uh, 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 topples 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, 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 air it’s 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 said is something like this. So for let’s go name, age in zip names ages, and then I could 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 covers. And then I could just print the I underscore color, no matter what. So you’re going, that is zip pretty useful. And yeah, definitely just cleans up the program a little bit.

*args & **kwargs

So the next shortcut I have for you is a little bit more advanced, but this is star arcs and star star quarks. Now ARG stands for arguments, positional arguments specifically, and quarks stands for key or arguments. Now positional argument is one in which position matters. So if you look at this, our Guan when I called this function, the first value I pass in will be ARG one, the second arc to the third arc three, hence they are positional the position in which I passed 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 funk to ARG two equals X, whatever I could do, our Guan 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 RX and star star quirks? 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 Topal, maybe a string that has all this stuff. I want to pass to a function. Well, the way that I can do this is something like this, right? I could go funk one. And then I could say arcs at index zero and then arcs at index one, or I could decompose this right, or break this down, unpack it and have, you know, ABC equals arcs, then pass ABC right here.

But there is a much faster way to do this. What I can actually do is write star arcs. Now what star arcs will do is unpack this and split this into all of the three individual items. So you can kind of imagine that star arcs removes this list right here and passes the values. 1, 2, 3, like that as positional arguments to this function. So when I go start arcs, you will see here that I get 1, 2, 3 printing out. And obviously let’s just change this to two, three shows two to three. Now, one of the best ways to visualize star arcs is to do the following. If I print arcs, notice we get a list. If I print star arcs, notice I get two to three. 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 two. Then I print three. So it would look like two to 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 two funk, two quarks, okay. So we’re looking at funk two and we’re looking at our keyword arguments right here. If I do one asterix and I pass porgs, notice I’m printing out arc two are Guan and Argh three. 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 argon is actually equal to the string. ARG two R two is equal to the string. ARG one, you can read the output and you can see what three equal to that’s because we’re just passing the keys as positional arguments.

However, if I do two astrics, 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 ARG two equals two, our Guan equals one. And what 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 ARG two is equal to two. Our Guan is equal to one and then Argh three is equal to three. That’s what it looks like when you do star star quarks like that.

  Top 5 python modules that are great for beginners

For & While Else

So the next short could I have view is one that many people do not know about in this is the four L’s or while else statement. Now, what this allows you to do is determine if you broke out of a for-loop or a wild loop without having to use a flak. 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 guys. 1, 2, 3, 4, 5, 6, and seven. What you’ll do oftentimes 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 four 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 will 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 will 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 L statement here. Now what the L 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 Ellis 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 four loop. There you go.

That’s as simple as it is, the L’s 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, um, that’s not going to work. I’m going to say, well, I is less than the land of search. I is equal to zero. Obviously a for-loop is better for this purpose. And I can 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 was all I wanted to show you the four LS and while Elsa statement.

Sort By Key

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 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 dot 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 lists. That makes sense. That’s intuitive. So we get negative 1, 1, 2, 3, 4, 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 it reversed equals true. And now if I do this, oh, 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 of 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 X one. 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 X one X one 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 X one, plus X, zero, and now we’ll sort it by the sum of the, uh, the values in this list. So if I do this here, uh, we get to, this is the lowest, then three, then five, then six, then seven, and then nine makes sense.

Now, in case the Lambda’s confusing, any of you, it’s the exact same as doing this. So I can define, say sort on our score function. This is going to take in X and I’m going to return X zero plus X one. Now, instead of passing the Lambda, what I would do is pass the sort underscore function it’s going to then return X Euro plus X one. 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 these sorted as well. I can pass LST and then key equals and anything that sorts in Python, you can usually pass this key parameter.

Avatar of Biên tập Viên

About: Biên tập Viên

A guy who love writing and inspire message.