Shahriar Kabir

Software Engineer

MCPD

OCJP

MCSE

Shahriar Kabir

Software Engineer

MCPD

OCJP

MCSE

Blog Post

11 Essential Python Tips And Tricks For Programmers

April 17, 2022 Python
11 Essential Python Tips And Tricks For Programmers

Python Tips And Tricks – Python is one of the most preferred languages out there. Its brevity and high readability make it so popular among all programmers.

So here are a few of the tips and tricks you can use to bring up your Python programming game.

11 Essential Python Tips And Tricks For Programmers

1. In-Place Swapping of Two Numbers.

x, y = 30, 40

print(x, y)

x, y = y, x

print(x, y)

Output:

30 40

40 30

 

2. Reversing a string in Python

a = “ShahriarRulz”

print(“Reverse is”, a[::-1])

Output:

Reverse is zluRriarhahS

 

3. Create a single string from all the elements in list

a = [“Shahriar”, “Rulz”]

print(” “.join(a))

Output:

Shahriar Rulz

 

4. Chaining Of Comparison Operators.

n = 10

result = 1 < n < 20

print(result)

result = 1 > n <= 9

print(result)

Output:

True

False

 

5. Print The File Path Of Imported Modules.

import os

import socket

print(os)

print(socket)

Output:

<module ‘os’ from ‘/usr/lib/python3.5/os.py’>

<module ‘socket’ from ‘/usr/lib/python3.5/socket.py’>

 

6. Use of Enums In Python.

class MyName:

Shahriar, For, Shahriar = range(3)

print(MyName. Shahriar)

print(MyName.For)

print(MyName. Shahriar)

Output:

2

1

2

 

7. Return Multiple Values From Functions.

def x():

return 1, 2, 3, 4

a, b, c, d = x()

print(a, b, c, d)

Output:

1 2 3 4

 

8. Find The Most Frequent Value In A List.

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]

print(max(set(test), key = test.count))

Output:

4

 

9. Check The Memory Usage Of An Object.

import sys

x = 1

print(sys.getsizeof(x))

Output:

28

 

10. Print string N times.

n = 2

a = “ShahriarRulz”

print(a * n)

Output:

ShahriarRulz ShahriarRulz

 

11. Checking if two words are anagrams

from collections import Counter

def is_anagram(str1, str2):

return Counter(str1) == Counter(str2)

# or without having to import anything

def is_anagram(str1, str2):

return sorted(str1) == sorted(str2)

print(is_anagram(‘zeek’, ‘eezk’))

print(is_anagram(‘zeek’, ‘peek’))

Output:

True

False

Thats all from 11 Essential Python Tips And Tricks For Programmers. See you in the next article.

Write a comment