Using Freshworks apps? Check out what we can do for you! Learn More

Back

30 Ways to Write Better Python Code – Part 2

simplifying python programming - 2

PythonPythonWith dynamic semantics, Python is an object-oriented, interpreted, high-level programming language. Python reduces the maintenance cost of the program as it has simple and easy to learn syntax that emphasizes readability. Thanks to its high-level built-in data structures for making it attractive for Rapid Application Development, as well as for using it as a scripting language. Python supports a wide range of libraries and a few of them are numpy, pandas, matpotlib, scipy, etc. coding is simple and easy to learn as it was developed, keeping in mind the needs of the developer. Python has always had a big developer community, and you can learn things quickly since you can get your doubts clarified quickly. Python coding ensures the developer optimally does the job. It has its libraries and modules that give you the liberty of coming up with your innovative solutions. In other words, it encourages you to improve the existing code and optimize the available solutions.

In Part 1, we saw the fundamentals of Python that are simple and straightforward. In Part 2, let’s explore further so that you get a better picture of the interesting ways of coding in Python.

Note: Please compile your code here for the best results.

1) Checking for Anagrams of Two Strings

Two strings are said to be anagrams if the characters in one string make up the other string. You can use the Counter method from the Collections module for this purpose.

For example,

Output

Anagram

Here both strings, string1 and string2, are made up of the same characters. Thus, they form an anagram.

2) Create a Number Sequence with Range

You can use the range() function to create a number sequence in Python. The syntax for a range function is as given below,

Syntax: range(start, end, step)

For example, you can create a list of odd numbers using the following code.

Output

[1, 3, 5, 7, 9, 11, 13, 15, 17]

3) Repeating an Element Multiple Times

Just like string multiplication, you can create a list made up of the same element multiple times with the help of the multiplication operator.

Output

[‘TechAffinity’, ‘TechAffinity’, ‘TechAffinity’, ‘TechAffinity’, ‘TechAffinity’]

Recommended Read: What is Python used for in Startups? Why Should a CTO Choose Python for Business in 2020?

4) Using Conditions in Ternary Operator

In Python, you will often come across nested conditional structures. But instead of using this, you can use a ternary operator and make it into a single line of code.

Syntax: Statement1 if True else Statement2

For example,

Output

100

5) List Comprehension in Python

You can easily create a list from another list using list comprehension. Take the case of generating a list of squares for a range of numbers from 1 to 10.

Case1 – Using Iterations
Output

[1, 4, 9, 16, 25, 36, 49, 64, 81]

Case2 – Using List Comprehension

Output

[1, 4, 9, 16, 25, 36, 49, 64, 81]

6) Convert Mutable to Immutable

You can use the frozenset() function to convert a mutable iterable into an immutable object. By freezing, you can stop an object from changing its value.

For example,

Output

Traceback (most recent call last):

  File “main.py”, line 3, in <module>

    my_list[3]=5

TypeError: ‘frozenset’ object does not support item assignment

Since you applied the frozenset() function on the list, the item value cannot be changed, and the assignment gets restricted.

Also Read: Java vs Python: Which programming language to pick?

7) Rounding Off with Floor and Ceil Functions

Python coding allows you to use math functions on floating numbers. As a result, you can use the floor and ceil functions on such numbers. These mathematical functions are imported from the math module in Python. Floor function returns an integer lesser than the floating value, and ceil function returns an integer higher than the floating value.

For example,

Output

98.0

99.0

8) Returning Boolean Values

You sometimes need to return boolean values based on the condition of certain parameters. Instead of using if-else statements, you can directly return the condition.

For example,

Case1- With If-Else Condition

Output

Eligible

Case2 – Without If-Else Condition
Output

Eligible

9) Creating Single-Line Functions with Lambda

Lambda is an anonymous function that you can use for creating single-line functions. It can take any number of arguments but can have only one expression. The syntax for a lambda function is given below.

Syntax: lambda arguments: expression

For example,

Output

6

10) Apply Function to All Elements in a List

You can use map() function to apply a particular function to all the elements in a given list. This higher-order function in Python is used to perform several useful tasks. Its syntax is given below. 

Syntax: map(function, iterable)

For example,

Output

[‘Empowering’, ‘Growth’]

Wrapping Up

As you have seen, Python makes it possible to accomplish tasks with minimal effort if we use it the right way. Please keep in mind that these Python coding practices will come in handy only if you regularly use and practice them. We hope that you have been able to pick up the aspects of Python coding that will prove useful as you progress in your developer journey. We shall bring you the remaining tricks in the final part of the series, which will help you even further. To stay updated with our latest posts, we encourage you to subscribe to our weekly newsletter.

At TechAffinity, our Python development team has experts who are on track with recent trends and deliver the best Python services to you. If you have any queries, share them with media@techaffinity.com or schedule a meeting with our experts.

Subscribe to Our Blog

Stay updated with latest news, updates from us