4 effective tips and tricks to write better Python code

Python is one of the most discussed programming languages among tech professionals at present. Not only for software development but also for machine learning and data science, Python is the preferred choice. Due to its fairly easy learning curve and mature and supportive community, new learners can get started easily. Also, hundreds of open-source libraries and frameworks, and the versatility and efficiency of Python make it a valuable programming language to add to your skills.

This article shares some tips and tricks for beginners and experienced programmers to write better Python code. The tips will help write more readable and faster code quickly.

1. Start using list comprehension instead of for loops 

For loops in Python code can cause unnecessary nesting that results in hard-to-read and maintain code. You can make your Python code much simpler with a list comprehension. It is a more straightforward and elegant way to create lists from existing lists. Using brackets, you can repeatedly execute each iteration with a single line of code. You can make your code time and space efficient by replacing loops and iterative statements with a list comprehension.

Here’s the usual syntax for list comprehension:

newList = [ expression(element) for element in oldList if condition ]

In practical applications, it is used like this:

# Loop iteration using list comprehension

List = [character for character in ‘HackerNoon’]

 # Displaying list

print(List)

# Output

# [‘H’, ‘a’, ‘c’, ‘k’, ‘e’, ‘r’, ‘N’, ‘o’, ‘o’, ‘n’]”

2. Using NotImplementedError for offensive programming

Python comes with an in-built NotImplementedError exception, a valuable feature for offensive programming. In offensive programming, developers avoid defensive principles when dealing with software bugs.

One example is when we control the input to align it with the format accepted by our code. It is not easy to sanitize every input, and it can be an inconvenience for future development.

Have a look at the code below in which we define a registering decorator and some functions:

import math

REGISTRY = {}

def register(name):

   def _decorator(fn):

     REGISTRY[name] = fn

     return fn

   return _decorator

@register(“relu”)

def rectified(x):

   return x if x > 0 else 0

@register(“sigmoid”)

def sigmoid(x):

   return 1/(1 + math.exp(-x))

def activate(x, funcname):

   if funcname not in REGISTRY:

     raise NotImplementedError(f”Function {funcname} is not implemented”)

   else:

     func = REGISTRY[funcname]

     return func(x)

print(activate(1.23, “relu”))

print(activate(1.23, “sigmoid”))

print(activate(1.23, “tanh”))

Here we used the NotImplementedError with a custom error message for the function activate(). The output of the code will be:

1.23

0.7738185742694538

Traceback (most recent call last):

  File “/Users/MLM/offensive.py”, line 28, in <module>  

print(activate(1.23, “tanh”))

  File “/Users/MLM/offensive.py”, line 21, in activate

   raise NotImplementedError(f”Function {funcname} is not implemented”)

NotImplementedError: Function tanh is not implemented

The result of the first two functions is printed, but the third function fails as we haven’t defined the tanh function yet.

This is an example of how you can use the NotImplementedError: in places in your code that still don’t meet the validity of the conditions but later on will have validation as the project proceeds.

3. Use generators to save memory 

In Python, the basic function of a generator is to evaluate the elements of a code on demand. As the syntax for list comprehension, here you use parentheses instead of square brackets. 

Here’s a code to generate the square of all even numbers in a list using generators: 

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(“The given list is:”, myList)

mygen = (element ** 2 for element in myList if element % 2 == 0)

print(“Elements obtained from the generator are:”)

for ele in mygen:

   print(ele)

The output:

The given list is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Elements obtained from the generator are:

4

16

36

64

100

Beginners might find it hard to decide how the list comprehension differs from generators, given that their syntax is almost identical. 

Unlike list or set comprehension, generator comprehension does not initialize any objects. This is how using a generator comprehension lowers the memory requirement for a program. 

4. Define default values in Dictionaries with .get() and .setdefault()

Beginners often struggle with providing a default value for the Dictionaries function in their Python code. You can forget about assignment default value with the use of .setdefault() and .get().

With the .setdefault() method, you can set dict[key]=default if there is no key for the dict function already. You set the .setdefault() like this:

dict.setdefault(key, default=None)

Example code:

a_dictionary = {“a”: 1, “b”: 2, “d”: 4}

a_dictionary.setdefault(“c”, 3)

print(a_dictionary)

The output of the above code would look like this:

{‘a’: 1, ‘b’: 2, ‘d’: 4, ‘c’: 3}

The same functionality can be achieved using the .get() method, but you pass a default value for the key here. Here’s how it works:

a_dictionary = {“a”: 1, “b”: 2, “d”: 4}

print(a_dictionary.get(“c”, 3))

print(a_dictionary)

The output of the above code:

3

{‘a’: 1, ‘b’: 2, ‘d’: 4}

Conclusion 

Python has scope in multiple fields, and as you learn the scope of the language, you will know more tricks to optimize your code.

Talent500 is looking for python developers who want to join dynamic engineering teams at some of the biggest global companies. Sign up here to know more.

 

Top 7 blogs that every mobile developer should follow

Mobile applications now make up a substantial part of our lives. We use them for everything from setting alarms to booking cabs and ordering meals. Businesses rapidly adapt to this digital transformation creating a massive demand for mobile developers.

Mobile app development is a dynamic domain, and new technologies, tools, and practices keep spurring in the industry. Keeping track of every recent change or trend for a mobile developer can be challenging. An easy way to keep up to date with the trends in the industry is to follow some quality mobile developer blogs. To help you, we picked the top blogs that mobile developers should follow.

1. Android developers blog

It is no surprise that the first featured developer blog on our list is Google’s Android Developers blog. If you are an Android app developer, chances are you are already familiar with the blog; if not, you are missing some great resources. Being the official Android blog, it is where you will find the latest news on the OS, product updates, and developers’ tips and tricks shared by Google engineers. As the contributors on this blog are Google developers, you get to learn from their hands-on experience in building Android apps. Several more insightful resources are shared on the Android developer’s blog, and it’s worth bookmarking.

2. iOS Dev Weekly

For iOS app developers, this one is a great resource to stay in touch with the latest market trends and innovations. The iOS Dev Weekly curates articles every week, hand-picked by its editors, who are iOS engineers. You can expect to discover exciting and inspiring articles on iOS mobile app development. Most of the articles shared on this developer blog are focused on Swift, hacks for iOS developers, quick tips, and other iOS tech-related categories. The blog also offers premium membership to become an insider and access its strong community of iOS developers.

3. Game Analytics blog

An excellent blog for mobile gaming app developers, Game Analytics blog shares hundreds of articles on development, app marketing advice, and motivational success stories. Game app development is a sophisticated venture, and this blog helps you keep track of innovative tools and technologies that can simplify mobile app development.

Game Analytics is an analytic platform helping game developers dive deeper into any part of game development by providing insightful data. You must follow this developer blog because it enables you to understand how analytics can be used within game app development. The articles are pretty insightful and provide actual tech guidance rather than clickbait titles.

4. Android Authority

With millions of followers on Twitter, Facebook, and YouTube, Android Authority remains one of the top tech blogs for android developers to follow. All the information you need to know about Android apps, games, phones, tablets, or laptops is available. The blog also features full review articles on mobile apps and devices and guides Android users about the best apps to install on their phones. This can be a great learning resource for Android app developers to understand the market trends and study popular apps. Android Authority is an excellent app developer blog for new and experienced developers.

5. Big Nerd Ranch

Big Nerd Ranch markets itself as a company that “teaches, designs & builds digital products.” What’s unique about this firm is that the founders were among the few engineers recruited by Steve Jobs back in 1997. One of the principal values of the company is its blog.

Big Nerd Ranch blog shares excellent practical app development tutorials for mobile developers. There are significant additional resources for designers and software engineers too. If you are interested in team building and mobile technology training, articles are available on the topic.

6. Ray Wenderlich’s blog 

Technically, it is not an average mobile developer blog but rather a resource full of tutorials. Ray Wenderlich offers articles on complete mobile app development spanning several technologies and platforms. In this blog, you will find articles on Flutter, Android, Kotlin, Unity, Swift, iOS, Dart, server-side Swift, and more. The RW community has junior and senior app developers learning from over 3000 tutorials offered by the blog.

7. Yalantis blog

Yalantis is a software engineering and IT consulting firm that offers mobile app development services to enterprise clients. On the Yalantis blog, there are hundreds of inspiring app development blogs. The company also shares business stories about how they tackled a challenge and provided a solution to the client through their services. It provides a learning opportunity for mobile developers to understand the practical application of the app development approach. 

Yalantis is another great developer blog to learn about the latest mobile app development trends and solutions. One particular section is the design articles sharing insights on how Yalantis’ design team creates impressive user experience.

Following these developer blogs will assist you in upskilling and staying afloat with the industry trends. For more insightful tips and articles on software development, website design, mobile apps, and more, you can follow the Talent500 blog.