25 Essential Python Snippets to Solve Everyday Coding Problems
This article presents 25 practical Python code snippets covering tasks such as sorting lists, sorting dictionaries, printing on a single line, merging dictionaries, reversing data, checking duplicates, filtering unique items, digitizing numbers, measuring byte size, finding similarity, memory usage, vowel extraction, palindrome testing, swapping values, random shuffling, error handling, and more, all with clear explanations.
Python is one of the top languages for web development, application development, security, and data science. To make your Python coding faster and simpler, here are 25 useful code snippets that address common everyday problems.
1. Sort a List
Quickly sort a list using the built‑in list.sort() method or the sorted() function.
lst = ["Mango", "PineApple", "Orange", "Apple"]
# method 1
lst.sort()
print(lst) # ['Apple', 'Mango', 'Orange', 'PineApple']
# method 2 – generic sorting
new_lst = sorted(lst)
print(new_lst) # ['Apple', 'Mango', 'Orange', 'PineApple']
# reverse sorting
new_lst = sorted(lst, reverse=True)
print(new_lst) # ['PineApple', 'Orange', 'Mango', 'Apple']2. Sort a Dictionary
Sort a dictionary by its values using a dictionary comprehension or dict() with sorted().
d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
# method 1
new_dict = {k: v for k, v in sorted(d.items(), key=lambda item: item[1])}
print(new_dict) # {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
# method 2
new_dict = dict(sorted(d.items(), key=lambda item: item[1]))
print(new_dict) # {0: 0, 2: 1, 1: 2, 4: 3, 3: 4}3. Print on the Same Line
Use the end parameter of print or sys.stdout.write to avoid automatic newlines.
# method 1
print("I'm a Python", end=" ")
print("Programmer")
# method 2
import sys
sys.stdout.write("I'm a Python")
sys.stdout.write(" Programmer")4. Merge Two Dictionaries
Combine two dictionaries into a new one with dict.update().
def merge_two_dict(x, y):
z = x.copy()
z.update(y)
return z
x = {"A": 1, "B": 2}
y = {"C": 3, "D": 4}
print(merge_two_dict(x, y)) # {'A': 1, 'B': 2, 'C': 3, 'D': 4}5. Reverse Data
Reverse strings or integers using slicing.
def reverse(data):
return data[::-1]
print(reverse("Python")) # nohtyP
print(reverse("23354")) # 453326. Check for Duplicates
Determine if a list contains duplicate elements.
def check_duplicates(lst):
return len(lst) != len(set(lst))
lst1 = [1, 2, 3, 3]
lst2 = [1, 2, 3]
print(check_duplicates(lst1)) # True
print(check_duplicates(lst2)) # False7. Filter Unique Items
Obtain a list of unique values by converting to a set and back.
mylist = [1, 2, 3, 2, 5, 6, 6, 5, 7]
unique = list(set(mylist))
print(unique) # [1, 2, 3, 5, 6, 7]8. Digitize a Number
Convert an integer into a list of its digits.
def digitize(num):
return list(map(int, str(num)))
print(digitize(321)) # [3, 2, 1]
print(digitize(900)) # [9, 0, 0]9. Byte Size of a String
Use len and encode to get the byte length of a string.
def byte_size(string):
return len(string.encode('utf-8'))
print(byte_size("hello")) # 5
print(byte_size("Python Programming")) # 1810. Find Similar Elements
Return the intersection of two lists.
def similarity(x, y):
return [item for item in x if item in y]
x = [1, 2, 3, 4, 5]
y = [1, 2, 3]
print(similarity(x, y)) # [1, 2, 3]11. Memory Usage of a Variable
Check how many bytes a variable occupies using sys.getsizeof.
import sys
var1 = 500
var2 = "Python"
print(sys.getsizeof(var1)) # 28
print(sys.getsizeof(var2)) # 5512. Get Vowels from a String
Extract vowels using a list comprehension.
def get_vowels(string):
return [ch for ch in string if ch in 'aeiou']
print(get_vowels("asert")) # ['a', 'e']
print(get_vowels("football")) # ['o', 'o', 'a']13. Palindrome Check
Verify whether a string reads the same backward.
def palindrome(string):
return string == string[::-1]
print(palindrome('mom')) # True
print(palindrome('bob')) # True
print(palindrome('desk')) # False14. Fast Value Swap
Swap two variables using tuple unpacking.
# old method
a = 5
b = 6
temp = a
a = b
b = temp
print(a, b) # 6 5
# new method
a, b = 5, 6
a, b = b, a
print(a, b) # 6 515. Random Shuffle
Shuffle a list in place with random.shuffle.
import random
lst = [1, 2, 3, 4, 5]
random.shuffle(lst)
print(lst) # e.g., [1, 2, 3, 5, 4]
random.shuffle(lst)
print(lst) # e.g., [4, 2, 5, 3, 1]16. Error Handling
Catch runtime errors without terminating the program.
try:
print(a) # NameError
except:
print(b) # NameError again
else:
print("Program is still running, Error is handled")17. Capitalize First Letter of Each Word
Use the title() method to capitalize words.
string1 = "python programming language"
print(string1.title()) # Python Programming Language
string2 = "learn python"
print(string2.title()) # Learn Python18. Get Head and Tail of a List
Retrieve the first and last elements of a list.
def head(lst):
return lst[0]
def tail(lst):
return lst[-1]
lst = [1, 2, 3, 4, 5]
print(head(lst)) # 1
print(tail(lst)) # 519. Prime Check
Determine whether a number is prime.
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
print(is_prime(11)) # True
print(is_prime(4)) # False20. Initialize List with Range
Create a list of integers within a given range and step.
def initialize_list(end, start=0, steps=1):
return list(range(start, end + 1, steps))
print(initialize_list(5)) # [0, 1, 2, 3, 4, 5]
print(initialize_list(7, 1)) # [1, 2, 3, 4, 5, 6, 7]
print(initialize_list(8, 1, 2)) # [1, 3, 5, 7]21. Convert to Binary
Convert an integer to its binary representation.
def convert_to_binary(num):
return bin(num)
print(convert_to_binary(900)) # 0b1110000100
print(convert_to_binary(300)) # 0b10010110022. Convert Word to List
Split a sentence into a list of words using regular expressions.
import re
def word_to_list(string, pattern='[a-zA-Z-]+'):
return re.findall(pattern, string)
print(word_to_list("Python")) # ['Python']
print(word_to_list("Are you a Programmer?")) # ['Are', 'you', 'a', 'Programmer']23. Split Method
Demonstrate different uses of the split() method.
# example 1
string = "I'm a Programmer"
print(string.split()) # ["I'm", 'a', 'Programmer']
# example 2
string = "I'm a Programmer"
print(string.split('a')) # ["I'm ", ' Progr', 'mmer']
# example 3
string = "I'm
a
Programmer"
print(string.split('
')) # ["I'm", 'a', 'Programmer']24. N‑Times String
Repeat a string multiple times without a loop.
s = "Data"
N = s * 5
print(N) # DataDataDataDataData
s = "Python"
N = s * 2
print(N) # PythonPython25. Flatten a List
Convert a nested list into a flat list.
def flatten_list(lst):
return [a for b in lst for a in b]
print(flatten_list([[1,2,3],[4,5],[7,8]])) # [1, 2, 3, 4, 5, 7, 8]
print(flatten_list([[1,2,3],[8,9]])) # [1, 2, 3, 8, 9]I hope these snippets are helpful and enjoyable for learning. Thanks for reading, and feel free to share them with friends who might benefit.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
