According to the most recent Forbes report, Python grew by 456% last year. Python is used by Netflix, IBM, and thousands of other businesses. Not to mention Dropbox. Python was also used to develop Dropbox. One can learn Python online in various ways and also Python is among the biggest skills to have, according to Dice, and the most popular programming language around the world, as per the Popularity of Programming Language Rankings. Let us discuss some of the ways to write better python code.
Why is it necessary to write Better Python Code?
To learn Python, you must know something and that’s why writing better Python code is important. Python code that is better and more efficient could assist in minimizing runtime and conserving computational resources. Evidently, the Python language was designed with readability in mind, based on the well-known observation that code is read far more frequently than it has been created. Python’s reasonably full collection of Code Style rules and Python Idioms is one reason for its good readability.
Without a question, Python is a cool language. However, there are a few Python angles that are somewhat more amazing than the standard Python stuff.
Here you will find 12 Python tips and tricks that have been hand-picked for you. Knowing these tricks would save you a significant amount of time.
Multiple Assignments
Multiple Assign is a method that enables you to assign the same value for multiple variables at the same time. Multiple variables might be assigned different values and even the same value. In Python, the = operator is used to assign values to the variables. On a single line, you might be able to assign values to multiple variables.
x=35
y=35
z=35
Instead of using this kind of declaration, use the following.
x = y = z = 35
String Concatenation
Whenever you need to concatenate a list of strings, use a for loop and add each element one at a time. That might be pointless, particularly if the list you possess is too long. Because strings in Python are immutable, each pair of concatenation might require copying the left and right strings into such a new string.
Using the join() function, as demonstrated below, is a superior option:
word = ['p', 'r', 'o', 'g', 'r', 'a','m']
word1 = "".join(word)
print(word1)
To build a python dictionary, combine two lists
Let’s pretend we got two lists: one with the students’ names and the other with their grades. But how can these two lists be combined into a single python dictionary? This could be done with the zip function and the code below:
students = ['Kia','Sia','Mia']
marks = [98,87,70]
dictionary = dict(zip(students, marks))
print(dictionary)
Get Method
If the key isn’t present, this approach will avoid you from getting a key error in the Dictionary. Rather than the bracket method [], which returns None instead of KeyError, just use the get method.
mydict = {1: "Java”, 2: "Swift", 3: "HTML"}
#Default Method
mydict[4] # KeyError
#Get Method
mydict.get(4) # None
Slicing a List
This trick will show you how to use the bracket approach to slice a list. [Start: Stop: Step] are the three parameters that will be applied. Let us take a look at the code below for an example.
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(mylist[3: 9: 3])
Lambda function
Another life-saving Python trick is lambda. It allows you to create functions with only one line of code. Take a look at the code snippet below.
num = 4
data = lambda x : x * 2
print(data(2))
Variable unpacking
In Python, unpacking is a method of assigning an iterable of values to a tuple (or list) of variables with a single assignment statement.
x, y = [4, 8]
#Output : x = 4, y = 8
x, *y = [3,6,9,12,15]
#Output : x = 3, y = [6,9,12,15]
x, *y, z = [3,6,9,12,15]
#Output : x = 3, y = [6,9,12], z = 15
Using sorted() function
Sorting any series in Python is simple thanks to the built-in method sorted(), which takes care of the majority of the work for you. sorted() always returns a list of sorted elements after sorting a sequence (list, tuple). Now, let’s look at how to sort a list of integers in ascending order.
sorted([4,7,2,8,1]) # [1,2,4,7,8]
Input as a Password
Possibly, you’ll be able to use input from the user like a password format using this method. The Python language includes a built-in library called ‘getpass.’ It enables you to take input in such an advanced way.
import getpass
userinput = getpass.getpass("Please Enter Password: ")
print(userinput)
Getting rid of unwanted characters
It entails the following steps: (left strip, right strip, and just strip)
Strip methods in Python can be used to remove whitespaces or even any specified character. For both sides, you could use a simple strip method, lstrip for the left side, and rstrip for the right side exclusively. See the following example to understand more clearly.
string="+++World Cup+++"
string=string.strip('+')
print(string)
When the code runs too fast: (Make Python Sleep)
You may want your code to be executed slowly at times. You could wish to illustrate something, or you might need to take a few steps at a time. The time library’s sleep approach is ideal for this.
Replace secs with any integer that represents seconds:
import time
time.sleep(secs)
Random numbers
When examining a model or the behavior of a program over a wide range of values, it is essential to generate random numbers. Whenever you need to generate random numbers, Python’s default random library can come in handy. The random module in Python could be used to produce such random numbers.
For an integer between the lower and upper boundaries, use randint:
import random
a=random.randint(5, 300)
print(a)
So well here you have it: we’ve compiled this 12 tricks long list of the best tricks to write better Python code that adheres to industry standards. We hope they will assist you in improving the quality of your code and maybe also be beneficial for your next project. Because Python is such a wide and well-developed language, there are certain to be some features we haven’t yet implemented. To learn python, you can use websites like python for beginners.
Please let us know if you have any other Python tricks to share!
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, I only recommend products or services I use personally and believe will add value to my readers.