Top 5 most interesting and usable python tricks in 2021.

Top 5 most interesting and usable python tricks in 2021.
Kumar Saptam

Kumar Saptam

The best and most interesting tips and tricks for python which can be used by any developer whether you are a beginner or a experienced developer, I promise you will definitely learn something from here.

In this blog we will talk about some of the most underrated and awesome tips of python which can make your life much easier than ever. You can get all code shown in this blog from this repository. If find any difficulty in any code or find them not working please report them in the comments, it will be helpful for me to solve the problem as soon as possible. Visit our blog if you find this post interesting or if not checkout it anyway you will surely find something interesting and new.

The 5 tips which we are going to discuss are:

  1. Using lambda for quick and single line functions to make your code shorter and much more comprehensive.
  2. Using slicing for smaller and faster list manipulations.
  3. Using threads for multiprocessing and faster code execution.
  4. Using sum to add items of an array quickly and efficiently.
  5. Compiling python programs into bytecode.

Now you may not find them as interesting as I have shown here because when I didn't knew these tricks specialy the threading one but now I know and you too. In simple words these are my favourites tricks which are available in python.

  • Using lambda for single line or short functions.
  • Using slicing for smaller and faster list manipulations.
  • Using threads for multiprocessing and faster code execution.
  • Using sum to add items of an array quickly and efficiently.
  • Compiling python programs into bytecode.

Using lambda for single line or short functions.

                            
#The lambda function
functionName=lambda variable: list(str(variable))[0]

#defining a string variable
a="MyLongCharacter"

#printing the output of our lambda function
print(functionName(a))
                        

What is lambda?

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

How lambda is different from a function ?

Lambda is a type of function which only interprets a single line of command. For example a function which can return first letter of any word. In this example we start by creating a varible named "functionName" and we give it a value of a lambda function.
The syntax of lambda function is
functionName = lambda x,y,z: x+y+z
Here the functionName is, yeah, your Function Name. And there are three variables named "x", "y", "z". These are parameters like you give in a normal function. OK, we have our function defined, now, how will this function return the value of x+y+z. Good Question. The lambda automatically returns any data if our single line code is returning something. And we all ( should ) know that x+y+z returns the sum of all the numbers. As we have seen in the IDLE of python.

Now let's see both functions and how do they compare.


#The lambda function
functionName=lambda variable: list(str(variable))[0]

#defining a string variable
a="MyLongCharacter"

#printing the output of our lambda function
print(functionName(a))

#The lambda function
def functionName:
    return list(str(variable))[0]

#defining a string variable
a="MyLongCharacter"

#printing the output of our lambda function
print(functionName(a))

#The lambda function
functionName=lambda variable: list(str(variable))[0]

#defining a string variable
a="MyLongCharacter"

#printing the output of our lambda function
print(functionName(a))

#The lambda function
def functionName:
    return list(str(variable))[0]

#defining a string variable
a="MyLongCharacter"

#printing the output of our lambda function
print(functionName(a))

Using slicing for smaller and faster list manipulations.

What is slicing in python?

Slicing is a method which makes us access a certain part of a list (array), tuples, and strings by the use of it's index. The syntax of slicing is simple:
mutableItem[start,end,step]

Here the mutableItem (a data strucutre which can be modified) is like a list, string, or tuple. The slicing works exactly same as a range() function in python. Which can take three integers. The first one will be from where it should start the second one is end and the last one is step how much step it should take to reach the next element in the data strucutre. For example if we have a list named

a = "alpha"
then when we will execute
a[2:3]
. This this will output us
p
. Because we have asked python to return elements from index 2 to 3. And if we look closely it did not return
h
  because python skips the last number. So if we want to return
ph
we need to write
a[2:4]
.

array=[1,2,3,4,5,6,7,8,9,0] #defined a list
string="1234567890"
sets=(1,2,3,4,5,6,7,8,9,0)

#Using slicing
print(array[0:4])
#Output => [1, 2, 3, 4]
print(string[0:4])
#Output => 1234  
print(sets[0:4])
#Output => (1, 2, 3, 4)
print(array[::-1])
#Output => [0,9,8,7,6,5,4,3,2,1]

Using threads for multiprocessing and faster code execution.

What is threading or threads in python?

Threading or also known as multiprocessing, is a concept of computers. In which two or more programs or process can be run simultaneously.

Threads have been around for a long time. An early example of a master/slave multiprocessor system is the Tandy/Radio Shack TRS-80 Model 16 desktop computer which came out in February 1982 . Threads were omnipresent in python. It functions with the help of cores and threads available in most of the modern CPUs. For example you can run two for loops simultaneously. Isn't that cool.

To use threads in python you need to import threading modue.


import threading

#our first function
def firstLoop():
    for i in range(5):
        print(i)

#our second function
def secondLoop():
    for i in range(5):
        print(i)

#our first thread
thread1=threading.Thread(target=firstLoop)
thread2=threading.Thread(target=secondLoop)

#starting our threads
thread1.start()
thread2.start()

#waiting for the threads to end
thread1.join()
print("Thread 1 ended")
thread2.join()
print("Thread two ended")

Code Explanation

First we import threading module. Then we create two functions with for loops inside it. I made two functions here because threading class only accepts functions on the target attribute. You can use any function you want as a process.

Using sum to add items of an array quickly and efficiently.

App

There are many functions which are prebuilt in python. But when it comes to adding all elements of a list we all use loops and counter additions to get the sum. But there is a simple way to do it. Which is by usin a builtin function known as

sum()
. This function sum is faster than age old loop based addition. I checked the speed of both of the functions and the results are:
sum => Total time taken 0.0
for loop => Total time taken 0.003001689910888672

I know they are very close but you need to write less code and you also get more performance, so there is not a reason to not use it.

The code

a=[1,2,3.0,5,6.0]
a=(1,2,3.0,4,5.0,6)
sum(a) # return the addition of all the elements ==> 21

Code explanation

We first write a data strucutre. The accepted data strucutre which can be used are lists and tuples, which can only contain support integers or float numbers. Then we use the function sum with parameter of a data structure.


Compiling python programs into bytecode.

App

Whenever you run a python program, python converts your code into machine code, which then can be interpreted and executed to give a desired program logic. But whenever we write a very big code python takes time to convert it into machine code. So we can compile the python file into machine code to help caching and speeding up your python program execution.

What is py compile?

Py compile is a library inbuilt into python which handles the conversion of human readable python code into machine code.

How to compile python or use py compile?

import py_compile
py_compile.compile("pythonFile.py")

Code Explanation

First we import py_compile module. Then we use

.compile()
function of py_comile module with an attribute of a python file path.

Comments are loading