10 essential Python tips and tricks for programmers

Counters | File handling | Python Methods and Functions

1. Replacing two numbers in place.

x, y = 10 , 20

print (x, y)

x, y = y, x

print (x, y)

Output:

 10 20 20 10 

2. Line breaking in Python

a = " GeeksForGeeks "

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

Output:

 Reverse is skeeGroFskeeG 

3. Create one row from all the elements in the list

a = [ "Geeks" , "For" , "Geeks" ]

print ( "" .join (a))

Exit:

 Geeks For Geeks 

4. Concatenation of comparison operators.

n = 10

result = 1 & lt; n & lt;  20

print (result)

result = 1 & gt; n & lt; = 9

print (result)

Exit:

 True False 

4. Type the path to the imported modules file.

import os; 

import socket; 

 

print (os)

print (socket)

Exit:

 & lt; module 'os' from' / usr / lib / python3.5 / os.py' & gt; & lt; module 'socket' from' /usr/lib/python3.5/socket.py'> 

5. Using Enums in Python.

class MyName:

Geeks, For, Geeks = range ( 3 )

 

print (MyName.Geeks )

print (MyName.For)

print (MyName.Geeks)

Exit :

 2 1 2 

6. Return multiple values ​​from functions.

def x ():

return 1 , 2 , 3 , 4

a, b, c, d = x ()

 

print (a, b, c, d)

Exit :

 1 2 3 4 

7. Find the most common value in the list.

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

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

Exit:

 4 

8. Check object memory usage.

import sys

x = 1

print (sys.getsizeof (x))

Exit :

 28 

9. Print a line N times.

n = 2

a = "GeeksforGeeks"

print (a * n); 

Exit:

 GeeksforGeeksPython.Engineering 

10. Checking if two words are anagrams

from collections import Counter

def is_anagram (str1, str2):

return Counter (str1) = = Counter (str2)

print (is_anagram ( 'geek' , 'eegk' ))

 

print (is_anagram ( 'geek' , 'peek' )) 

Exit :

 True False 

Links:
1. 10 neat Python tricks beginners should know
2. 30 Essential Python Tips and Tricks for Programmers