Python is TIOBE’s programming language of the year for 2020 and is also ranked number one as per the PYPL (PopularitY of Programming Language) site. The language is easy to learn, read and understand. The Python tips given in this article will help readers to write code that is concise and easy to understand.
The Python programming language, a general-purpose programming language created by Guido Van Rossum in the late 1980s, is a free and open source language incorporating multiple programming paradigms. Rossum was motivated to create this language as he was not happy with both the C language and the UNIX shell, the tools he had access to at that time. The C language forced him to manually manage memory and the language did not have enough libraries of reusable code. UNIX shells could not handle complex logic and were slow in execution.
Python is easy to learn, read and understand, and is ideal for beginners to learn and start coding in a few hours. It has an interpreter which makes it easy to test even a single line of code quickly. The Python language is versatile, flexible, extensible and powerful. Open source libraries are available for use in various areas including Big Data, machine learning, deep learning, data analytics, simulation and scientific programming, image processing, natural language processing, robotics, face recognition, numerical computation, data visualisation, Web development, etc.
Suitable for day-to-day tasks, Python reduces the software development time sharply by three to five times compared to other popular languages like C/C++ and Java. It supports dynamic typing and does automatic memory management. Python is TIOBE’s programming language of the year 2020 and is now ranked number one as per the PYPL (PopularitY of Programming Language) site.
I have compiled a few tips and tricks of the Python programming language which will be useful for beginners. Some of the tips are related to the way Python allows some common tasks and constructs to be written differently. This makes the code concise and easier to read. Some other tips give a way to do some tasks using a different method instead of the usual one.
Multiple assignments
Python allows multiple assignments in a single statement. The first value on the right is assigned to the first variable on the right, and so on.
>>> a, b = 1, 2 >>> print (a, b) 1 2 >>>
A single value could be assigned to multiple variables in the following way:
>>> a = b = c = 5 >>> print (a, b, c) 5 5 5 >>>
If multiple values are assigned to a single variable, they are assigned as a tuple:
>>> a = 1,2,3 >>> print (a) (1, 2, 3) >>>
Swapping of values
Python allows swapping of the values of two variables in a single statement without having to use a third variable, like in other languages:
>>> num1, num2 = 10, 20 >>> print (num1, num2) 10 20 >>> >>> num1, num2 = num2, num1 >>> print (num1, num2) 20 10 >>>
Combining a list into a string
A list of values can be concatenated into a single string by adding the elements of the list using a loop. But this is inefficient, particularly if the list is long. A Python string is immutable. Hence, a new string is created during every iteration. The same can be done easily by using the join() function:
>>> namelist = [“ram”, “shyam”, “rahul”, “ravi”, “ashok”] >>> namestr = “”.join(namelist) >>> print (namestr) ramshyamrahulraviashok >>>
Printing a list of strings with comma as a separator
Printing a list of strings as output separated by a comma can be done easily in the following way:
>>> names = [“Anand”, “Rahul”, “Sairam”, “Shiva”] >>> print (*names, sep = ‘,’) Anand,Rahul,Sairam,Shiva >>>
The ‘*’ in the above line is used for unpacking an iterable (a list in this case). The sep parameter specifies the character to use to separate the objects in the list. The default is ‘ ‘ (space).
Creating a list of unique elements
Removing duplicates in a list is easy using the set data structure, as the latter does not allow duplicate elements. The list can be converted to sets, which automatically eliminates duplicates. The set is converted back to the list and the new list will then have only unique elements.
>>> numlist = [1,1,2,2,3,3,3,4,4,5,5] >>> numlist = list (set (numlist)) >>> print (numlist) [1, 2, 3, 4, 5] >>>
The interactive ‘_’ operator
The ‘_’ (single underscore) is used as a temporary variable to save the result of the last executed expression only in the Python interactive shell, and its value can be printed or used in other ways.
>>> a = 8 >>> b = 7 >>> a * b 56 >>>_ 56 >>>
Returning multiple values from a function
Functions defined in Python can return multiple values unlike languages like C/C++ or Java, which allow only a single value to be returned. The multiple values are returned as a tuple.
>>> #sample of Python function returning multiple values >>> def test(): a = 1 b = 2 c = 3 return a, b, c >>> d, e, f = test() >>> print (d, e, f) 1 2 3 >>>
Chaining of comparison operators
Python allows the use of multiple comparisons in a single expression by chaining the comparison operators. The expression returns True only if all the comparisons are true and returns False otherwise.
>>> a = 10 >>> 5 < a < 20 True >>>
The above is equal to writing ( a > 5) and (a < 20).
Another example is given below:
>>> 20 < a < 50 False
The above is equal to writing ( a > 20) and (a < 50).
Use of ternary operator for conditional assignment
Like many other programming languages, Python also has a facility that gives the effect of a ternary operator. Python defines a conditional expression, which helps to convert the if..else statement to a one-line conditional expression. This results in making the code concise due to multiple lines being reduced to a single line, which is also easier to read. The syntax is:
<expression1> if <condition> else <expression>
The condition is evaluated and if the result is True, expression1 is evaluated; if the result of the condition is False, expression2 is evaluated.
>>> num = 55 >>> “odd” if num % 2 == 1 else “even” ‘odd’ >>>
A condition having three possibilities can be written using nested if else in a single line:
>>> x, y, z = 30.5, 45.0, 76.8 >>> “x is max” if x > y and x > z else “y is max” if y > x and y > z else “z is max” ‘z is max’ >>>
Simplified if construct
When multiple tests are required in an if construct, the code is usually written in the following way:
>>> if num == 4 or num == 8 or num == 12 or num == 16:
The above could be simplified to:
>>> if num in [4,8,12,16]:
The result is the same, but the code is easier to read.
Initialising a list with a repetitive value
In case you need to create a list with repetitive values, the easiest way is to do the following:
>>> lst = [1,2,3] * 6 >>> print (lst) [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] >>>
Reversing a string
Reversal of a string is one of the frequent tasks done in string processing. One easy way to reverse a string in Python is by slicing the strings:
>>> name = “Sai Kumar” >>> print (a[::-1]) >>> ‘ramuK iaS’ >>>
The Python tips given in this article help in writing concise and easy to understand code. The tips covered here are the most common and basic ones. There are innumerable such tips in Python and you will keep discovering new ways of doing things even after coding for a few years in this language. The best way to learn is to start coding. Happy Pythoning!