This content originally appeared on DEV Community and was authored by Nisha Karitheyan
Python is loved because itβs short, sweet, and powerful. With just a few lines, you can do things that take much longer in other languages.
Here are some cool tricks that will make your code cleaner, smarter, and way more fun to write.
1. In-Place Swapping of Two Numbers
Who needs a third variable when Python does the magic for you?
x, y = 5, 42
print(x, y)
x, y = y, x
print(x, y)
Output:
5 42
42 5
2. Reversing a String Like a Pro
No loop, no stressβjust slice it backwards.
word = "PythonRocks"
print("Reverse is", word[::-1])
Output:
Reverse is skcoRnothyP
3. Joining a List into a String
Turn a list of words into a single sentence.
words = ["Coffee", "Makes", "Coding", "Better"]
print(" ".join(words))
Output:
Coffee Makes Coding Better
4. Chaining Comparisons
Instead of writing long conditions, Python lets you chain them.
n = 15
print(10 < n < 20) # True
print(5 > n <= 14) # False
5. Print the File Path of Imported Modules
import os
import math
print(os)
print(math)
Output:
<module 'os' from 'C:/Python311/Lib/os.py'>
<module 'math' (built-in)>
6. Use of Enums in Python
Enums are great for giving names to values.
class Colors:
Red, Green, Blue = range(3)
print(Colors.Red)
print(Colors.Green)
print(Colors.Blue)
Output:
0
1
2
7. Returning Multiple Values From a Function
def get_coordinates():
return 10, 20, 30
x, y, z = get_coordinates()
print(x, y, z)
Output:
10 20 30
8. Most Frequent Value in a List
nums = [3, 7, 3, 2, 7, 7, 1, 3, 7, 2]
print(max(set(nums), key=nums.count))
Output:
7
9. Check Memory Usage of an Object
import sys
x = "Hello World"
print(sys.getsizeof(x))
Output:
60
10. Print a String Multiple Times
word = "Python"
print(word * 3)
Output:
PythonPythonPython
11. Check if Two Words are Anagrams
def is_anagram(s1, s2):
return sorted(s1) == sorted(s2)
print(is_anagram('listen', 'silent'))
print(is_anagram('hello', 'world'))
Output:
True
False
12. Sort a Dictionary by Key and Value
data = {3: "banana", 1: "apple", 2: "cherry"}
print(sorted(data.items(), key=lambda a: a[1])) # by value
print(sorted(data.items(), key=lambda a: a[0])) # by key
Output:
[(1, 'apple'), (3, 'banana'), (2, 'cherry')]
[(1, 'apple'), (2, 'cherry'), (3, 'banana')]
Final Thoughts
And there you goβ Python tricks to make your code cleaner and your brain happier!
Try them out in your next project and show off your Python wizardry .
This content originally appeared on DEV Community and was authored by Nisha Karitheyan