They vs Me print(“Python Shortcuts”)

6 min readMar 14, 2019

Overview:

As everyone knows, python is known for its short code and greater functionality. In my mind, the main concept of Python is to code less and work more. But still there are some people who shifted from other programming languages into python and use the same concept in codes to get the work done. I was one of them, but slowly slowly i learnt many things that helped me to keep my code shorten. In this article i am going to give you some Tricks that will help you to reduce your code size. Reducing the size or shortening your code results in speeding of the tool.

List Comprehensions:

Many people don’t know about it, List comprehensions provide a concise way to create lists. when we try to store items of one list into another list after doing some operations on it, we simply use the following method.

>>> vals = []
>>> for value in collection:
if condition:
vals.append(expression)

But you know, there is a way to shorten this process known as List Comprehension. The following code is equivalent to the above code.

>>> vals = [expression 
for value in collection
if condition]

Consider an example for the above method.

>>> even_squares = [x * x for x in range(10) if not x % 2]
>>> even_squares
[0, 4, 16, 36, 64]

Custom switch statements:

As every python programmer knows, Python doesn’t have switch/case statements so we can use if, elif and else conditions to get that done, but what if we use some other method to short our code and speed up our code.
let’s look into switch statement made through if conditions.

def switch_if(operator, x, y):
if operator == 'add':
return x + y
elif operator == 'sub':
return x - y
elif operator == 'mul':
return x * y
elif operator == 'div':
return x / y
else:
return None
>>> switch_if('mul', 2, 8)
16
>>> switch_if('unknown', 2, 8)
None

See, its working fine like a switch statement. But what if we use a dictionary in single return statement instead of if conditions. :O w0h0 that sounds awesome. Lets look into the following code.

def switch_dict(operator, x, y):
return {
'add': lambda: x + y,
'sub': lambda: x - y,
'mul': lambda: x * y,
'div': lambda: x / y,
}.get(operator, lambda: None)()
>>> switch_dict('mul', 2, 8)
16
>>> switch_dict('unknown', 2, 8)
None

See, working as exact the same as above, but what we got is a simple and short code.

Custom Ternary Operator:

As you know, Python don’t have ternary operator. It has only if else conditions but you can make your own. Here is how can you make your own custom Ternary Operator using Tuple indexing.

("false state","true state")[condition]

In the above code, it the condition becomes true, the string, value or function to the right side will be executed and if the condition becomes false, the left side will be executed.

Here is how it works, as we know condition returns either False or True which is equivalent to 0 and 1 respectively and the above tuple has 2 values which can be accessed by 0 and 1 respectively.

Let’s look into the following code to understand better.

x = 4
y = 8
z = ("false state", "true state")[y>x]
>>> z
true state

Swapping:

The act of swapping two variables refers to mutually exchanging the values of the variables. It is very simple and everyone knows how to do it, but Python gives us a simple way to get it done.

Most programmers that shifted from other Programming languages like C, C#, Java, php etc. write the following code even in Python to swap the variables without knowing that there is a pretty simple way in Python to do it.

a = 23
b = 42
# The "classic" way to do it
# with a temporary variable:
tmp = a
a = b
b = tmp

But you know Python also let us use this short-hand:

a, b = b, a

Boom, Swapping of a and b done.

Functions:

Every programmer use functions a lot, as these are known as first-class citizens in Python. You know? It can be passed as arguments to other functions, returned as values from other functions, and assigned to variables and stored in data structures. Consider the following program to understand what i mean.

>>> def myfunc(a, b):
... return a + b
...
>>> funcs = [myfunc]
>>> funcs[0]
<function myfunc at 0x0000025127571E18>
>>> funcs[0](2, 3)
5

As you saw, we defined a function, stored in a list and then used it later, like that we can pass it as an argument to another function and return as well.

Argument unpacking:

Ever wondered what the *args and **kwargs that you keep seeing in Python functions mean? I certainly did. So I did some searching and it turns they're pretty nifty, not to mention useful.

That * and the ** operators both perform two different, but complementary operations depending on where they're used.

def myfunc(*args,**kwargs):
pass

They perform an operation called ‘packing’. True to it’s name, what this does is pack all the arguments that this method call receives into one single variable, a tuple called args. You can use any variable name you want, of course, but args seems to be the most common and Pythonic way of doing things.

Once you have this ‘packed’ variable, you can do things with it that you would with a normal tuple. args[0] and args[1] would give you the first and second argument, respectively. If you convert the args tuple to a list you can also modify, delete and re-arrange items in it.

So how do you pass these packed arguments to another method? Here’s where unpacking comes in to play:

def myfunc(x,y,z):
print(x,y,z)
tup = (10,20,30)
dicti = {'x':1, 'y':2, 'z':3}
>>> myfunc(*tup)
10 20 30

>>> myfunc(**dicti)
1 2 3

So there’s the same * operator again, but this time it's in the context of a method call. What it does now is explode the args array and call the method as if you'd typed in each variable separately. Text from article.

Dictionary.get() default argument:

As everyone know about the dictionary, as it has an index and a value. To access and get the value from the dictionary there are several ways but some popular are by indexing and .get() function of the dictionary. we will talk about the dictionary function .get() . It takes an argument which will be any index in the dictionary, if it exists it will return its related value else it will return None.

But what if we want something else than None if the index we passed didn’t found. The .get() function of dictionary takes second argument which is returned instead of None when the passed index not found in the dictionary. Lets look into the following code.

name_by_id = {
363: "Maria",
991: "Jazib",
441: "Khalid",
}
def welcome(uid):
return "Hi %s!" % name_by_id.get(uid, "there")
>>> welcome(363)
Hi Maria!
>>> welcome(33333)
Hi there!

See! when we passed an unknown (33333) argument to .get() function of dictionary it returned the text we passed into as second argument instead of None value.

Merging two dictionaries:

Every work can be done by many methods, but the one that helps us use less space and give us a clean code is the best method. There are plenty of ways to marge two dictionaries but you know, you can merge two dictionaries by ** operator which will also override the duplicates indexes and values.

Let’s look into the following code.

>>> x = {'a': 1, 'b': 2}
>>> y = {'b': 3, 'c': 4}

>>> z = {**x, **y}
>>> z
{'a': 1, 'b': 3, 'c': 4}

In this example, Python merges dictionary keys in the order listed in the expression, overwriting duplicates from left to right.

Credits:

  • Thanks to Dan at Real Python, for sending me helpful codes of python that helps me to reduce and learn more things in python.
  • Arguments Unpacking is copied from this site.

Thanking:

Thanks to you for reading the article, if you need my help in making any tool or for ordering something you can contact me on my email: ijazkhan095@gmail.com or my upwork account: Ijaz Ur Rahim

--

--

Ijaz Ur Rahim
Ijaz Ur Rahim

Written by Ijaz Ur Rahim

Just a Newbie with some Random Penetrating and Programming Skills. https://ijazurrahim.com/

No responses yet