Education

Top 5 Essential Python Coding Tips and Tricks for Programmers

If you ask any Python programmer to tell about the strengths of Python, he will quote brevity and high readability as the most influencing ones. In this Python tutorial, we’ll cover many essential Python Coding Tips and tricks that will authenticate the above two points.

We’ve been collecting these useful shortcuts (tips & tricks) since we started using Python. And what’s best than sharing something we know and which could benefit others as well.

So today, we’re back with one more set of essential Python tips and tricks. All these tips can help you minify the code and optimize execution. Moreover, you can readily use them in live projects while working on regular assignments.

Here Are The Top 5 Essential Python Coding Tips and Tricks

1. In-place swapping of two numbers

Python provides an intuitive way to do assignments and swapping in one line. Please refer to the below example.

x, y = 10, 20
print(x, y)
 
x, y = y, x
print(x, y)
 
#1 (10, 20)
#2 (20, 10)

The assignment on the right seeds a new tuple. While the left one instantly unpacks that (unreferenced) tuple to the names <a> and <b>.

Once the assignment is through, the new tuple gets unreferenced and flagged for garbage collection. The swapping of variables also occurs at eventually.

2. Chaining of comparison operators

Aggregation of comparison operators is another trick that can come handy at times.

n = 10
result = 1 < n < 20
print(result)

# True

result = 1 > n <= 9
print(result)

# False

3. Use of Ternary operator for conditional assignment

Ternary operators are a shortcut for an if-else statement and also known as conditional operators.

[on_true] if [expression] else [on_false]

Here are a few examples which you can use to make your code compact and concise.

The below statement is doing the same what it is meant to i.e. “assign 10 to x if y is 9, otherwise assign 20 to x“. We can though extend the chaining of operators if required.

x = 10 if (y == 9) else 20

Likewise, we can do the same for class objects.

x = (classA if y == 1 else classB)(param1, param2)

In the above example, classA and classB are two classes and one of the class constructors would get called.

Below is one more example with a no. of conditions joining to evaluate the smallest number.

def small(a, b, c):
	return a if a <= b and a <= c else (b if b <= a and b <= c else c)
	
print(small(1, 0, 1))
print(small(1, 2, 2))
print(small(2, 2, 3))
print(small(5, 4, 3))

#Output
#0 #1 #2 #3

We can even use a ternary operator with the list comprehension.

[m**2 if m > 10 else m**4 for m in range(50)]

#=> [0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401]

 

4. Work with multi-line strings

The basic approach is to use backslashes which derive itself from C language.

multiStr = "select * from multi_row \
where row_id < 5"
print(multiStr)

# select * from multi_row where row_id < 5
One more trick is to use the triple-quotes.
multiStr = """select * from multi_row 
where row_id < 5"""
print(multiStr)

#select * from multi_row 
#where row_id < 5

The common issue with the above methods is the lack of proper indentation. If we try to indent, it’ll insert whitespaces in the string.

So the final solution is to split the string into multi lines and enclose the entire string in parenthesis.

multiStr= ("select * from multi_row "
"where row_id < 5 "
"order by age") 
print(multiStr)

#select * from multi_row where row_id < 5 order by age

5. Storing elements of a list into new variables

We can use a list to initialize a no. of variables. While unpacking the list, the count of variables shouldn’t exceed the no. of elements in the list.

testList = [1,2,3]
x, y, z = testList

print(x, y, z)

#-> 1 2 3

 

Related Articles

Back to top button