
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
10 Interesting Python Cool Tricks
With the increase in popularity of the Python programming language, more and more features are becoming available for Python developers. Usage of these features helps us to write efficient code.
In this article, we will see 10 Python tricks that are very frequently used.
Reversing a List
We can reverse a given list by using the reverse() function. It returns the elements of the current list in reverse order. It works with both numeric and string datatypes.
Example
Let's see how to use the reverse() function in your Python program to reverse a list of strings:
List = ["Shriya", "Lavina","Sampreeti" ] List.reverse() print(List)
On executing the code, it will reverse the list and print the output as:
['Sampreeti', 'Lavina', 'Shriya']
Print List elements in any Order
If you need to print the values of a list in a different order, you can assign the list to a series of variables, and in the print() statement, you can mention the order in which you want to print the list.
Example
In the following example, we will define a list and print the list in a different order using a series of variables:
List = [1,2,3] w, v, t = List print(v, w, t ) print(t, v, w )
Running the above code gives us the following result:
2 1 3 3 2 1
Using Generators inside Functions
A Python generator is an expression that generates values one by one. We can use generators directly inside a function. Using generators in your program saves memory, as the generated values are not stored.
Example
In the below example, we find the sum using a generator directly as an argument to the sum function:
print(sum(i for i in range(10)))
Running the above code displays the sum of the first 10 integer numbers :
45
Using the zip() Function
When we need to combine many iterator objects, like lists, to get a single list from them, we can use the zip() function. This function accepts a variable number of iterable objects as parameters and rearranges the elements as per the index positions and returns them as an iterable.
The elements at the 0th index of all the given iterables are stored in the 0th iterable (of the resultant list), and the elements at the 1st index of all the given iterables are stored in the 1st iterable, and so on (similar to the transpose of a matrix).
Example
In the Python program given below, we are using the zip() function to group three different tuples.
Year = (1999, 2003, 2011, 2017) Month = ("Mar", "Jun", "Jan", "Dec") Day = (11, 21, 13, 5) print(list(zip(Year, Month, Day)))
The above code will display the following result:
[(1999, 'Mar', 11), (2003, 'Jun', 21), (2011, 'Jan', 13), (2017, 'Dec', 5)]
Swap two Numbers using Single line of Code
Typically, when we are swapping numbers, we will store values in a temporary variable. But, with the following Python trick, we can swap the values of two variables using one line of code, without using any temporary variables.
x, y = y, x
Example
In the following example, we are swapping two numbers in a single line of code:
x, y = 11, 34 print("Before: ") print("x = ", x) print("y = ", y) x, y = y, x print("After: ") print("x = ", x) print("y = ", y)
The result after running the code:
Before: x = 11 y = 34 After: x = 34 y = 11
Transpose a Matrix
When we convert columns of a matrix into rows, we call it the Transpose of a matrix. In Python, we can achieve it by using loops that iterate through the elements in the matrix and change their places.
However, a more easy solution is to use the zip() function (discussed above).
Example
In the following script, we are using the zip() function with the "*" operator to unzip a list, which will produce a transpose of the given matrix:
x = [[31,17], [40 ,51], [13 ,12]] print(list(zip(*x)))
Running the above code gives us the following result:
[(31, 40, 13), (17, 51, 12)]
Print a string N Times
The usual approach in any programming language to print a string multiple times is to use a loop. But, Python has a simple trick which needs a string, "*" operator, and a number inside the print() function.
Example
Here is an example Python program:
str ="Point"; print(str * 3);
Running the above code will print the string 3 times:
PointPointPoint
Reversing List Elements Using List Slicing
The slice operator is used to retrieve a part of an iterable in Python. This operator has 3 values -
- start: Starting position of the desired itereable.
- stop: Ending position of the desired itereable.
- step: Increment needed between each element.
We can reverse the order of elements in a list using the slicing operator by passing the step value as -1.
Example
In the following Python program, we are reversing the list elements using the slice operator:
# Reversing Strings list1 = ["a", "b", "c", "d"] print(list1[::-1]) # Reversing Numbers list2 = [1, 3, 6, 4, 2] print(list2[::-1])
Output after running the above code is as follows:
['d', 'c', 'b', 'a'] [2, 4, 6, 3, 1]
Find the Factors of a Number
When we need to find the factors of a number, we can use a for loop and check the divisibility of that number with the iteration index.
Example
The following Python program prints the factors of the given number:
f = 32 print("The factors of", f, "are:") for i in range(1, f + 1): if f % i == 0: print(i)
Running the above code gives us the following result:
The factors of 32 are: 1 2 4 8 16 32
Checking the Usage of Memory
We can check the amount of memory consumed by each variable that we declare by using the sys.getsizeof() function.
Example
As you can see in the example below, different string lengths will consume different sizes of memory:
import sys a, b, c,d = "abcde" ,"xy", 2, 15.06 print(sys.getsizeof(a)) print(sys.getsizeof(b)) print(sys.getsizeof(c)) print(sys.getsizeof(d))
Running the above code gives us the following result ?
46 43 28 24
Conclusion
We have discussed 10 cool Python tricks in this article. These tricks will help you save some time in writing codes and at the same time, you will be able to write shorter and cleaner code in your upcoming projects.