**Code Refactoring**
🤷 What is code refactoring, and why is it important?
Code refactoring means re-writing our code to improve:
In the following, I am presenting three tips that can be directly implemented in Python.
Tip #1: Use Enumerate
Programmers coming from other languages (especially C/C++) tend to use the increment of an index to do stuff within a loop. Python has a built-in function that allows us to do the same thing with fewer lines of code. To keep track of an index in a for loop, use the enumerate function.
# Index Increment
i=0
for x in something:
i=i+1
# do stuff
# can be replaced by enumerate:
for i, x in enumerate(something):
# do the same stuff
Recommended by LinkedIn
Tip #2: Use list comprehensions
List comprehensions are an excellent way to reduce code space, make your code more pythonic, and even make your code run faster! In the example below, you can see how to replace a normal for loop with a list comprehension.
# Typical for loop
collector_list=[]
for x in something:
collector_list.append(x)
# can be replaced by a list comprehension
collector_list=[x for x in something]
Tip #3: Replace try & except with conditional expressions
# a typical try & except such as:
try:
data=float(data)
except:
pass
# can be replaced by a conditional expression, such that:
data= float(data) if data.isnumeric() else data
A few notes regarding the try-except expression. In general, this construction should always be used with an explicit error (e.g: ZeroDivisionError) or avoided altogether (such as in our example above). The benefit of avoiding the try-catch is not just the additional space that we gain, but also the fact that such a construction might lead us to not address directly issues that might prove to be crucial in the late development stage.
I hope that you found this article helpful.
Take care,
Christos