12 Fun Python Tricks That’ll Make You Look Like a Pro 🐍✨

  • Thread starter Thread starter Nisha Karitheyan
  • Start date Start date
N

Nisha Karitheyan

Guest
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?

Code:
x, y = 5, 42
print(x, y)
x, y = y, x
print(x, y)

Output:

Code:
5 42 
42 5

2. Reversing a String Like a Pro πŸ”
No loop, no stressβ€”just slice it backwards.

Code:
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.

Code:
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.

Code:
n = 15
print(10 < n < 20) # True
print(5 > n <= 14) # False

5. Print the File Path of Imported Modules πŸ—‚οΈ
Code:
import os
import math
print(os)
print(math)

Output:

Code:
<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.

Code:
class Colors:
Red, Green, Blue = range(3)
print(Colors.Red)
print(Colors.Green)
print(Colors.Blue)

Output:

Code:
0
1
2

7. Returning Multiple Values From a Function 🎁
Code:
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 πŸ”₯

Code:
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 πŸ’Ύ

Code:
import sys
x = "Hello World"
print(sys.getsizeof(x))

Output:

60

10. Print a String Multiple Times 🎢

Code:
word = "Python"
print(word * 3)

Output:

PythonPythonPython

11. Check if Two Words are Anagrams πŸ”

Code:
def is_anagram(s1, s2):
return sorted(s1) == sorted(s2)
print(is_anagram('listen', 'silent'))
print(is_anagram('hello', 'world'))

Output:

Code:
True
False

12. Sort a Dictionary by Key and Value πŸ“Š

Code:
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:

Code:
[(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 πŸ§™β€β™‚οΈ.

Continue reading...
 


Join 𝕋𝕄𝕋 on Telegram
Channel PREVIEW:
Back
Top