Useful Python Tips and Tricks

Useful Python Tips and Tricks

Python is an extremely popular language and is used by many software developers.  It is one of the simplest languages to choose, especially if you are just starting out with coding.  This is due to its simplicity as well as code readability.  The question is, are there any tips or tricks that can be used when working on Python to make coding easier?

There are a plenty of tricks that can be used to improve your coding in Python! If you practice these continuously then you will gain an abundance of skills and understanding when it comes to the Python programming language.

The Benefits of Using Python

Support Libraries

Python come with a large library that includes things such as internet protocols, string operations, web services tools and operating system interfaces. There are also many high use programming tasks that have already been scripted into the standard library. These assist the user to significantly reduce the length of code that has to be written.

Third Party Modules

The Python Package Index contains a number of third-party modules that enables Python to interact with most of the other languages and platforms that are available.

Speed and Productivity

Python has a clean object-oriented design which enables enhanced process control capabilities as well as the ability to enable strong integration and text processing capabilities. It has its own unit testing framework which contributes towards the increase in speed and productivity. Python is an extremely beneficial program to use when it comes to building complex multi-protocol network applications.

Learning and Support

Python offers its users excellent readability together with uncluttered simple-to-learn syntax. This helps beginner users to utilise this programming language with ease. The code style guidelines provide a set of rules made to facilitate the formatting of code.  There is also an excellent resource bank to assist new users with continued learning of the language.

Community Development and Open Source

Python language is free to use and distribute and is also driven by a large community that collaborates its code through the hosting of conferences and mailing lists for its modules.

User-friendly Data Structures:

Python has a built-in list and dictionary data structure that can be utilised to construct fast runtime data structures. It also provides the option of high-level data typing which assists to reduce the length of support code that is needed during the coding process.

Valuable Python Tricks to Learn

  Multiple assignment for variables  Python allows its users to assign values for more than one variable in a single line. The variables can be separated using commas and the one-liners can be used for multiple assignments.   This can be used for assigning multiple values for multiple variables or multiple values for a single variable name.   For example here is a problem statement in which the user has had to assign the values 50 and 60 to the variables a and b. The code will look like the following:   a = 50
b = 60
print(a,b)
print(type(a))
print(type(b))
  Output 50 60
<class ‘int’>
<class ‘int’>
  Condition 1:  Values equal to Variables Each value will be stored in all the variables when the variables and values of multiple assignments are equal:   a , b = 50 , 60
print(a,b)
print(type(a))
print(type(b))
  Output 50 60
<class ‘int’>
<class ‘int’>
  Both of the programs give the same result which is a great benefit of using one-line value assignments.   Condition 2: Values greater than Variables In this example the numbers of value have been increased. The multiple values can be assigned to a single variable. When assigning more than one value to a variable the Python user needs to use an asterisk before the variable name:   a , *b = 50 , 60 , 70
print(a)
print(b)
print(type(a))
print(type(b))
  Output 50
[60, 70]
<class ‘int’>
<class ‘list’>
  You will see that the first value will be assigned to the first variable and the second variable will take a collection of values from the given values. This creates a list type object.   Condition 3: One Value to Multiple Variables Here we are able to assign a value to more than one variable. Each variable is separated by using an equal to symbol:   a = b = c = 50
print(a,b,c)
print(type(a))
print(type(b))
print(type(c))
  Output 50 50 50
<class ‘int’>
<class ‘int’>
<class ‘int’>
Swapping two variablesSwapping is the process of exchanging the values of two variables with each other. This can be useful in many operations in computer science. There are two methods that can be used by the programmer to swap the values:   Method 1 – Using a temporary variable This method uses a temporary variable to store some data. The following code is written with temporary variable name: a , b = 50 , 60
print(a,b)
temp = a+b  #a=50 b=60 temp=110
b = a       #a=50 b=50 temp=110
a = temp-b  #a=60 b=50 temp=110
print(“After swapping:”,a,b)
Output 50 60
After swapping: 60 50
  Method 2:  Without using a temporary variable The following code will swap the variable without using a temporary variable: a , b = 50 , 60
print(a,b)
a = a+b  #a=110 b=60
b = a-b  #a=110 b=50
a = a-b  #a=60  b=50
print(“After swapping:”,a,b)
Output 50 60
After swapping: 60 50
  Method 3: Optimal Solution in Python This is a different approach to the previous ones that have been mentioned. In this approach the programmer can use the concept of swapping: a , b = 50 , 60
print(a,b)a , b = b , a
print(“After swapping”,a,b)
Output 50 60
After swapping 60 50
 
Reversing a string  There is a way in which to reverse a string in python. This concept is known as slicing. A user is able to reverse any string by using the symbol [:-1] after the variable name:   my_string = “MY STRING”
rev_string = my_string[::-1]
print(rev_string)
Output GNIRTS YM  
Splitting words in a line  There is no special algorithm required for splitting the words in a line. The user can use the keyword split() for this purpose. There are two methods that can be used:   Method 1: Using iterations   my_string = “This is a string in Python”
start = 0
end = 0
my_list = []for x in my_string:
    end=end+1
    if(x==’ ‘):
        my_list.append(my_string[start:end])
        start=end+1
my_list.append(my_string[start:end+1])
print(my_list)
Output [‘This ‘, ‘is ‘, ‘a ‘, ‘string ‘, ‘in ‘, ‘Python’]   Method 2: Using the split function   my_string = “This is a string in Python”
my_list = my_string.split(‘ ‘)
print(my_list)
Output [‘This ‘, ‘is ‘, ‘a ‘, ‘string ‘, ‘in ‘, ‘Python’]  
List of words into a lineHere the Python user is able to convert a list of words into a single line by using join function. The syntax for using join function is:   Syntax: “ ”.join(string) my_list = [‘This’ , ‘is’ , ‘a’ , ‘string’ , ‘in’ , ‘Python’]
my_string = ” “.join(my_list)
Output This is a string in Python  
Create number sequence with rangeThe function range() is very useful for creating a sequence of numbers and can also be beneficial in many code snippets. The syntax for a range function is as follows:   Syntax: range(start, end, step) Let us try to create a list of even numbers. my_list = list(range(2,20,2))
print(my_list)
Output [2, 4, 6, 8, 10, 12, 14, 16, 18]  
Repeating the element multiple times  The user is able to create a list filled with an element multiple times by using the multiplication operator as follows:   my_list = [3]
my_list = my_list*5
print(my_list)
Output [3, 3, 3, 3, 3]  
Printing a string multiple times  Use the multiplication operator to print a string multiple times. Here is a very easy way in which to repeat a string:   n = int(input(“How many times you need to repeat:”))
my_string = “Python\n”
print(my_string*n)
Output How many times you need to repeat:3
Python
Python
Python
 
Find  the occurrence of all the elements in listIf the user needs to know the occurrence of all the unique elements in a list, then they are able to select the collection module. This collections module has some amazing features and the Counter method gives a dictionary with the element and occurrence pair. From collections import Counter and then do the following:
my_list = [1,2,3,1,4,1,5,5]
print(Counter(my_list))
Output Counter({1: 3, 5: 2, 2: 1, 3: 1, 4: 1})  
Using conditions in Ternary Operator  Most times in the Python Program the user needs to use nested conditional structures. Instead of using this structure there is a single line that can be replaced with the help of ternary operator. See the syntax below:   Syntax: Statement1 if True else Statement2 age = 25
print(“Eligible”) if age>20 else print(“Not Eligible”)
Output Eligible  
List comprehensionThis is a very compact way in which to create a list from another list. Looking at the codes below, the first one is written using simple iteration whereas the second one is created using list comprehension:   square_list = []
for x in range(1,10):
    temp = x**2
    square_list.append(temp)
print(square_list)
Output [1, 4, 9, 16, 25, 36, 49, 64, 81] Using List Comprehension square_list = [x**2 for x in range(1,10)]
print(square_list)
Output [1, 4, 9, 16, 25, 36, 49, 64, 81]  
Creating functions in one line  Lambda is an anonymous function within Python that creates functions in one line. See the syntax for the Lambda function below:   Syntax: lambda arguments: expression x = lambda a,b,c : a+b+c
print(x(10,20,30))
Output 60  
Iterating with a zip function  The zip function enables the process of iterating more than one iterable by making use of loops. The syntax shown below is used to code two lists that are getting iterated simultaneously:   list_1 = [‘a’,’b’,’c’]
list_2 = [1,2,3]
for x,y in zip(list_1, list_2):
    print(x,y)
Output a 1
b 2
c 3
 
Returning multiple values from a function  A python function can return more than one value without any extra need. The user can just return the values by separating them by commas as shown below:   def function(n):
    return 1,2,3,4
a,b,c,d = function(5)
print(a,b,c,d)
Output 1 2 3 4  
Filtering the values using the filter function  The filter function is used for filtering some values from an iterable object. See below:   Syntax: filter(function, iterable) def eligibility(age):
    return age>=24
list_of_age = [10, 24, 27, 33, 30, 18, 17, 21, 26, 25]
age = filter(eligibility, list_of_age)print(list(age))
Output [24, 27, 33, 30, 26, 25]  
Merging two dictionaries  In python a user can merge two dictionaries without using any specific method. The code given below is an example that can be used for merging two dictionaries:   dict_1 = {‘One’:1, ‘Two’:2}
dict_2 = {‘Two’:2, ‘Three’:3}
dictionary = {**dict_1, **dict_2}
print(dictionary)
Output {‘One’: 1, ‘Two’: 2, ‘Three’: 3}  
Combining two lists into a dictionary  By using zip function the user can create a dictionary from two lists:   list_1 = [“One”,”Two”,”Three”]
list_2 = [1,2,3]
dictionary = dict(zip(list_1, list_2))
print(dictionary)
Output {‘Two’: 2, ‘One’: 1, ‘Three’: 3}  
Getting the size of an object  The memory size varies based on the type of object. The user is able to get the memory of an object by using the getsizeof() function from the sys module as shown below:   import sys
a = 5
print(sys.getsizeof(a))
Output 28  
Calculating execution time for a program  Python can also be used to calculate the execution time for a program:   import time
start = time.clock()
for x in range(1000):
    pass
end = time.clock()
total = end – start
print(total)
Output 0.00011900000000000105
Removing duplicate elements from a list  When an element occurs more than one time it is called a duplicate element. Duplicate elements can be removed by doing the following:   my_list = [1,4,1,8,2,8,4,5]
my_list = list(set(my_list))
print(my_list)
Output [8, 1, 2, 4, 5]  
Printing a monthly calendar in python  The Calendar module has many functions related to date-based operations. A user is able to print a monthly calendar by using the following code:   import calendar
print(calendar.month(“2020″,”06”))
Output      June 2020
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
 
Using Lambda with Map function  This function can be replaced by a lambda function in Python. See the following syntax to create a square list of numbers:   my_list = [1, 2, 3, 4, 5]
new_list = map(lambda x: x*x, my_list)
print(list(new_list))
Output [1, 4, 9, 16, 25]  
Applying function for all elements in list  Map is a higher order function that applies to a particular function for all the elements in list:   Syntax: map(function, iterable) my_list = [“felix”, “antony”]
new_list = map(str.capitalize,my_list)
print(list(new_list))
Output [‘Felix’, ‘Antony’]  
Returning Boolean Values  In some cases the user may have to return a boolean value by checking the conditions of certain parameters. Instead of writing if else statements, the Python user can directly return the condition. The following will produce the same output:   Method 1: Using If Else Condition   def function(n):
    if(n>10):
        return True
    else:
        return False
n = int(input())
if(function(n)):
    print(“Eligible”)
else:
    print(“Not Eligible”)
  Method 2: Without If Else Condition   def function(n):
    return n>10n = int(input())
print(“Eligible”) if function(n) else print(“Not Eligible”)
Output 11
Eligible
 
Rounding off with Floor and Ceil  Floor and Ceil are mathematical functions that can be used on floating numbers. The floor function returns an integer smaller than the floating value and the ceil function returns the integer greater than the floating value. To use these functions the math module needs to be imported:   import math
my_number = 18.7
print(math.floor(my_number))
print(math.ceil(my_number))
Output 18
19
 
Joining Two strings using the addition operatorThis function is used to join various strings. Use the addition operator (+) to do this:   a = “I Love “
b = “Python”
print(a+b)
Output I Love Python  
More than one conditional operators  When wanting to combine two or more conditional operators in a program, logical operators can be used. The same result can be obtained by chaining the operators. If the user needs to print something when a variable has a value greater than 10 and less than 20 for example, the code will look as follows:   a = 15
if (a>10 and a<20):
    print(“Hi”)
Instead of this we can combine the conditional operator into single expression. a = 15
if (10 < a < 20):
    print(“Hi”)
Output Hi  
Finding the most frequent element in a list  The following tip will help you to get the most frequent element from a list:   my_list = [1,2,3,1,1,4,2,1]
most_frequent = max(set(my_list),key=my_list.count)
print(most_frequent)
Output 1  
Checking for the anagram of two strings  Here, the user is able to make use of the same Counter method from the collection’s module:   from collections import Counter
my_string_1 = “RACECAR”
my_string_2 = “CARRACE”if(Counter(my_string_1) == Counter(my_string_2)):
    print(“Anagram”)
else:
    print(“Not Anagram”)
Output Anagram  
Converting mutable into immutable  The function frozenset() is used to convert a mutable iterable into an immutable object. By using this the user can freeze an object from changing its value:   my_list = [1,2,3,4,5]
my_list = frozenset(my_list)
my_list[3]=7
print(my_list)
Output Traceback (most recent call last):
  File “<string>”, line 3, in <module>
TypeError: ‘frozenset’ object does not support item assignment
As we applied the frozenset() function on the list, the item assignment is restricted.  

Other Handy Python Tips, Tricks and Cheat Sheets

SetListDictionary
add() clear() pop() union() issuperset() issubset() intersection() difference() isdisjoint() setdiscard() copy()append() copy() count() insert() reverse() remove() sort() pop() extend() index() clear()copy() clear() fromkeys() items() get() keys() pop() values() updates() setdefault() popitem()    
StringListTupleSetDictionary
ImmutableMutableImmutableMutableMutable
Ordered/IndexedOrdered/IndexedOrdered/IndexedUnorderedUnordered
Empty StringEmpty List=[]Empty tuple=()Empty set=set()Empty dictionary={}
String with single element = “H”List with single item=[“Hello”]Tuple with single item=(“Hello:,)Set with single item={“Hello”}Dictionary with single item ={“Hello”:1}
It can store any data type str,list,set,tuple,int and dictionaryIt can store any data type str, list, set, tuple.int and dictionaryIt can store data types (int,str,tuple) but not (list, set, dictionary)Inside of dictionary key can be int, str and tuple only values can be of any data type int,str,list,tuple,set and dictionary

Visit: https://www.youtube.com/watch?v=_uQrJ0TkZlc to learn more about Python tips and tricks.

Leave a Reply

Your email address will not be published.