Tuesday, 18 February 2025

25 Insanely Useful Python Code Snippets For Everyday Problems

 


๐Ÿ“ 1. Swap Two Variables Without a Temp Variable


a, b = 5, 10
a, b = b, a
print(a, b)

Output:

10 5

๐Ÿ“ 2. Check if a String is a Palindrome


def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam"))

Output:


True

๐Ÿ”ข 3. Find the Factorial of a Number

from math import factorial
print(factorial(5))

Output:

120

๐ŸŽฒ 4. Generate a Random Password


import secrets, string
def random_password(length=10): chars = string.ascii_letters + string.digits + string.punctuation return ''.join(secrets.choice(chars) for _ in range(length))
print(random_password())

Output:


e.g., "A9$uT1#xQ%"

๐Ÿ”„ 5. Flatten a Nested List


def flatten(lst):
return [i for sublist in lst for i in sublist]
print(flatten([[1, 2], [3, 4]]))

Output:


[1, 2, 3, 4]

๐ŸŽญ 6. Check if Two Strings are Anagrams


from collections import Counter
def is_anagram(s1, s2):
return Counter(s1) == Counter(s2)

print(is_anagram("listen", "silent"))

Output:


True

๐Ÿ› ️ 7. Merge Two Dictionaries

d1, d2 = {'a': 1}, {'b': 2}
merged = {**d1, **d2}
print(merged)

Output:

{'a': 1, 'b': 2}

๐Ÿ“… 8. Get the Current Date and Time

from datetime import datetime
print(datetime.now())

Output:


2025-02-18 14:30:45.123456

๐Ÿƒ 9. Find Execution Time of a Function

import time
start = time.time() time.sleep(1)
print(time.time() - start)

Output:


1.001234 (approx.)

๐Ÿ“‚ 10. Get the Size of a File

import os
print(os.path.getsize("example.txt"))

Output:


e.g., 1024 (size in bytes)

๐Ÿ”Ž 11. Find the Most Frequent Element in a List


from collections import Counter
def most_frequent(lst): return Counter(lst).most_common(1)[0][0]

print(most_frequent([1, 2, 3, 1, 2, 1]))

Output:

1

๐Ÿ”ข 12. Generate Fibonacci Sequence


def fibonacci(n):
a, b = 0, 1 for _ in range(n): yield a a, b = b, a + b

print(list(fibonacci(10)))

Output:


[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

๐Ÿ”„ 13. Reverse a List in One Line


lst = [1, 2, 3, 4]
print(lst[::-1])

Output:

[4, 3, 2, 1]

๐Ÿ” 14. Find Unique Elements in a List

print(list(set([1, 2, 2, 3, 4, 4])))

Output:

[1, 2, 3, 4]

๐ŸŽฏ 15. Check if a Number is Prime


def is_prime(n):
return n > 1 and all(n % i for i in range(2, int(n**0.5) + 1))

print(is_prime(7))

Output:

True

๐Ÿ“œ 16. Read a File in One Line


print(open("example.txt").read())

Output:


Contents of the file

๐Ÿ“ 17. Count Words in a String

def word_count(s):
return len(s.split())

print(word_count("Hello world!"))

Output:

2

๐Ÿ”„ 18. Convert a List to a Comma-Separated String

lst = ["apple", "banana", "cherry"]
print(", ".join(lst))

Output:

apple, banana, cherry

๐Ÿ”€ 19. Shuffle a List Randomly

import random
lst = [1, 2, 3, 4] random.shuffle(lst)
print(lst)

Output:

e.g., [3, 1, 4, 2]

๐Ÿ”ข 20. Convert a List of Strings to Integers

lst = ["1", "2", "3"]
print(list(map(int, lst)))

Output:

[1, 2, 3]

๐Ÿ”— 21. Get the Extension of a File

print("example.txt".split(".")[-1])

Output:

txt

๐Ÿ“ง 22. Validate an Email Address


import re
def is_valid_email(email): return bool(re.match(r"[^@]+@[^@]+\.[^@]+", email))

print(is_valid_email("test@example.com"))

Output:


True

๐Ÿ“ 23. Find the Length of the Longest Word in a Sentence


def longest_word_length(s):
return max(map(len, s.split()))

print(longest_word_length("Python is awesome"))

Output:

7

๐Ÿ”  24. Capitalize the First Letter of Each Word

print("hello world".title())

Output:


Hello World

๐Ÿ–ฅ️ 25. Get the CPU Usage Percentage


import psutil
print(psutil.cpu_percent(interval=1))

Output:

e.g., 23.4

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (118) AI (152) Android (25) AngularJS (1) Api (6) Assembly Language (2) aws (27) Azure (8) BI (10) Books (251) Bootcamp (1) C (78) C# (12) C++ (83) Course (84) Coursera (298) Cybersecurity (28) Data Analysis (24) Data Analytics (16) data management (15) Data Science (217) Data Strucures (13) Deep Learning (68) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (17) Finance (9) flask (3) flutter (1) FPL (17) Generative AI (47) Git (6) Google (47) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (41) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (186) Meta (24) MICHIGAN (5) microsoft (9) Nvidia (8) Pandas (11) PHP (20) Projects (32) Python (1218) Python Coding Challenge (884) Python Quiz (342) Python Tips (5) Questions (2) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (19) SQL (45) Udemy (17) UX Research (1) web application (11) Web development (7) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)