1. In-place Swapping Of Two Numbers

Python provides an intuitive way to do swapping in one line. Please refer to the below example: a, b = 10, 20 print (a, b) a, b = b, a print (a, b) Output: 10, 20 20,10

2. Reversing string in python

If u want to reverse the string writing one line of code then follow trick used below: X= gnihtyrevenevespot print (“Reverse is”, x[ ::-1]) Output: Reverse is Topseveneverything

3.Print the file of imported modules

If you want to know the absolute location of modules imported in your code, then use the below trick: 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’>

4.Return multiple values from function

If you want to return multiple values from single function and you want to do it by writing 1 line code then check this trick: def x (); return 1, 2, 3, 4 a, b, c, d = x () print (a, b, c, d) Output: 1 2 3 4

5.To find most frequent element in the list

When you new to check the count of particular element use this: Top = [1, 2, 3, 4, 3, 3, 2, 1, 4, 4, 4] Print(max(set(top), key = test.count)) Output: 4

6.Check The Memory Usage Of An Object

When u create a object and you want to know its memory usage follow following syntax: import sys a = 1 print(sys.getsizeof(a)) Output: 28

7. Checking if two words are anagrams

When you want to sort a string alphabetically you use these few lines of code: 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('topseven', 'eenopstv')) print(is_anagram('topseven, 'topsix')) Output: True False


Nishit Jain