Python is one of the most preferred languages out there. Its brevity and high readability makes it so popular among all programmers. So here are few of the tips and tricks you can use to bring up your Python programming game. 1. In-Place Swapping Of Two Numbers.
Python3
x, y = 10, 20
print(x, y)
x, y = y, x
print(x, y)
|
2. Reversing a string in Python
Python3
a = "GeeksForGeeks"
print("Reverse is", a[::-1])
|
Output:
Reverse is skeeGroFskeeG
3. Create a single string from all the elements in list
Python3
a = ["Geeks", "For", "Geeks"]
print(" ".join(a))
|
4. Chaining Of Comparison Operators.
Python3
n = 10
result = 1 < n < 20
print(result)
result = 1 > n <= 9
print(result)
|
4. Print The File Path Of Imported Modules.
Python3
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'>
5. Use Of Enums In Python.
Python3
class MyName:
Geeks, For, Geeks = range(3)
print(MyName.Geeks)
print(MyName.For)
print(MyName.Geeks)
|
6. Return Multiple Values From Functions.
Python3
def x():
return 1, 2, 3, 4
a, b, c, d = x()
print(a, b, c, d)
|
7. Find The Most Frequent Value In A List.
Python3
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))
|
8. Check The Memory Usage Of An Object.
Python3
import sys
x = 1
print(sys.getsizeof(x))
|
9. Print string N times.
Python3
n = 2
a = "GeeksforGeeks"
print(a * n)
|
Output:
GeeksforGeeksGeeksforGeeks
10. Checking if two words are anagrams
Python3
from collections import Counter
def is_anagram(str1, str2):
return Counter(str1) == Counter(str2)
def is_anagram(str1, str2):
return sorted(str1) == sorted(str2)
print(is_anagram('geek', 'eegk'))
print(is_anagram('geek', 'peek'))
|
11. Sorting the dictionary according to key and value
Python3
x={1:3,4:2,5:1,2:9}
print(sorted(x.items(),key=lambda a:a[1]))
print(sorted(x.items(),key=lambda a:a[0]))
|
References: 1.10 Neat Python Tricks Beginners Should Know 2.30 Essential Python Tips And Tricks For Programmers
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...