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 write efficient and cleaner code.

In this article, we will explore 10 Python tricks that can make your code more concise and efficient.

Reversing a List

We can reverse a given list using the reverse() function. It modifies the original list in place and works with both numeric and string datatypes.

Example

Let's see how to use the reverse() function to reverse a list of strings ?

names = ["Shriya", "Lavina", "Sampreeti"]
names.reverse()
print(names)

The output of the above code is ?

['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 use tuple unpacking to assign list elements to variables, then print them in any sequence you want.

Example

In the following example, we will define a list and print it in different orders using tuple unpacking ?

numbers = [1, 2, 3]
w, v, t = numbers
print(v, w, t)
print(t, v, w)

The output of the above code is ?

2 1 3
3 2 1

Using Generators Inside Functions

A Python generator expression generates values one by one. We can use generator expressions directly inside functions to save memory, as the generated values are not stored but computed on demand.

Example

In the below example, we find the sum using a generator expression directly as an argument to the sum function ?

print(sum(i for i in range(10)))

The output shows the sum of numbers from 0 to 9 ?

45

Using the zip() Function

When we need to combine multiple iterable objects like lists, we can use the zip() function. This function accepts multiple iterable objects and combines elements at corresponding positions.

The elements at the same index positions from all iterables are grouped together, similar to transposing a matrix.

Example

In the following example, we use the zip() function to combine 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 output shows grouped elements from corresponding positions ?

[(1999, 'Mar', 11), (2003, 'Jun', 21), (2011, 'Jan', 13), (2017, 'Dec', 5)]

Swap Two Numbers Using Single Line

Python allows swapping variables without using temporary variables through tuple unpacking. This makes the code cleaner and more readable.

Example

In the following example, we swap two numbers in a single line ?

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 output shows the values before and after swapping ?

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 this efficiently using the zip() function with the unpacking operator.

Example

In the following script, we use the zip() function with the * operator to transpose a matrix ?

matrix = [[31, 17],
          [40, 51],
          [13, 12]]
print(list(zip(*matrix)))

The output shows the transposed matrix ?

[(31, 40, 13), (17, 51, 12)]

Print a String N Times

Instead of using loops, Python provides a simple way to repeat strings using the * operator. This multiplies the string by the specified number.

Example

Here is an example showing string repetition ?

text = "Point"
print(text * 3)

The output shows the string repeated 3 times ?

PointPointPoint

Reversing List Elements Using List Slicing

The slice operator is used to retrieve parts of an iterable in Python. It has three parameters: start, stop, and step. We can reverse a list by using a step value of -1.

Example

In the following example, we reverse 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])

The output shows both lists in reverse order ?

['d', 'c', 'b', 'a']
[2, 4, 6, 3, 1]

Find the Factors of a Number

To find factors of a number, we can use a for loop and check divisibility using the modulus operator.

Example

The following program finds and prints all factors of a given number ?

number = 32
print("The factors of", number, "are:")
for i in range(1, number + 1):
    if number % i == 0:
        print(i)

The output shows all factors of 32 ?

The factors of 32 are:
1
2
4
8
16
32

Checking Memory Usage

We can check the memory consumed by variables using the sys.getsizeof() function. This helps in optimizing memory usage in applications.

Example

The following example shows memory usage for different data types ?

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))

The output shows memory size in bytes for each variable ?

50
45
28
24

Conclusion

These 10 Python tricks can significantly improve your code's efficiency and readability. From list manipulation to memory optimization, these techniques help you write more Pythonic and professional code. Practice using these tricks to become a more effective Python developer.

Updated on: 2026-03-25T06:09:22+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements