22 Handy Python Code Snippets Every Developer Should Know

This article presents 22 practical Python code snippets—from extracting vowels and capitalizing words to merging dictionaries, measuring execution time, shuffling lists, and chunking data—offering concise solutions for everyday programming tasks and helping readers write cleaner, more efficient code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
22 Handy Python Code Snippets Every Developer Should Know

Python is a practical programming language that helps solve everyday problems. This article introduces 22 useful Python code snippets that let you handle common tasks such as extracting vowels, capitalizing words, printing a string multiple times, merging dictionaries, measuring execution time, swapping variables, checking duplicates, filtering false values, getting byte size, checking memory usage, detecting anagrams, sorting lists and dictionaries, retrieving the last list element, joining lists into a string, checking palindromes, shuffling lists, converting case, formatting strings, searching substrings, printing on the same line, and chunking lists.

1. Get Vowels

def get_vowels(string):
    return [ch for ch in string if ch in "aeiou"]

print(get_vowels("animal"))   # ['a', 'i', 'a']
print(get_vowels("sky"))      # []
print(get_vowels("football")) # ['o', 'o', 'a']

2. Capitalize First Letter

def capitalize(string):
    return string.title()

print(capitalize("shop"))                # Shop
print(capitalize("python programming")) # Python Programming
print(capitalize("how are you!"))       # How Are You!

3. Print String N Times

n = 5
string = "Hello World "
print(string * n)  # Hello World Hello World Hello World Hello World Hello World

4. Merge Two Dictionaries

def merge(dic1, dic2):
    dic3 = dic1.copy()
    dic3.update(dic2)
    return dic3

dic1 = {1: "hello", 2: "world"}
 dic2 = {3: "Python", 4: "Programming"}
print(merge(dic1, dic2))
# {1: 'hello', 2: 'world', 3: 'Python', 4: 'Programming'}

5. Measure Execution Time

import time
start_time = time.time()

def fun():
    a = 2
    b = 3
    c = a + b

fun()
end_time = time.time()
print("Your program takes:", end_time - start_time)

6. Swap Variable Values

a = 3
b = 4
a, b = b, a
print(a, b)  # 4 3

7. Check for Duplicates

def check_duplicate(lst):
    return len(lst) != len(set(lst))

print(check_duplicate([1,2,3,4,5,4,6]))  # True
print(check_duplicate([1,2,3]))          # False

8. Filter False Values

def filtering(lst):
    return list(filter(None, lst))

lst = [None, 1, 3, 0, "", 5, 7]
print(filtering(lst))  # [1, 3, 5, 7]

9. Byte Size of a String

def byte_size(string):
    return len(string.encode("utf8"))

print(byte_size("Python"))  # 6
print(byte_size("Data"))    # 4

10. Memory Usage of Variables

import sys
var1 = "Python"
var2 = 100
var3 = True
print(sys.getsizeof(var1))  # 55
print(sys.getsizeof(var2))  # 28
print(sys.getsizeof(var3))  # 28

11. Anagram Check

from collections import Counter

def anagrams(str1, str2):
    return Counter(str1) == Counter(str2)

print(anagrams("abc1", "1bac"))  # True

12. Sort Lists

my_list = ["leaf", "cherry", "fish"]
my_list1 = ["D", "C", "B", "A"]
my_list2 = [1, 2, 3, 4, 5]

my_list.sort()          # ['cherry', 'fish', 'leaf']
my_list1.sort()         # ['A', 'B', 'C', 'D']
print(sorted(my_list2, reverse=True))  # [5, 4, 3, 2, 1]

13. Sort Dictionary

orders = {"pizza": 200, "burger": 56, "pepsi": 25, "Coffee": 14}
sorted_dic = sorted(orders.items(), key=lambda x: x[1])
print(sorted_dic)
# [('Coffee', 14), ('pepsi', 25), ('burger', 56), ('pizza', 200)]

14. Retrieve Last List Element

my_list = ["Python", "JavaScript", "C++", "Java", "C#", "Dart"]
print(my_list[-1])   # Dart
print(my_list.pop()) # Dart

15. Join List with Commas

my_list1 = ["Python", "JavaScript", "C++"]
my_list2 = ["Java", "Flutter", "Swift"]
print("My favourite Programming Languages are " + ", ".join(my_list1))
# My favourite Programming Languages are Python, JavaScript, C++
print(", ".join(my_list2))
# Java, Flutter, Swift

16. Palindrome Check

def palindrome(data):
    return data == data[::-1]

print(palindrome("level"))  # True
print(palindrome("madaa"))  # False

17. Shuffle List Randomly

from random import shuffle
my_list1 = [1,2,3,4,5,6]
my_list2 = ["A","B","C","D"]
shuffle(my_list1)
shuffle(my_list2)
print(my_list1)  # e.g., [4, 6, 1, 3, 2, 5]
print(my_list2)  # e.g., ['A', 'D', 'B', 'C']

18. String Case Conversion

str1 = "Python Programming"
str2 = "IM A PROGRAMMER"
print(str1.upper())  # PYTHON PROGRAMMING
print(str2.lower())  # im a programmer

19. String Formatting

str1 = "Python Programming"
str2 = "I'm a {}".format(str1)
print(str2)  # I'm a Python Programming

str2 = f"I'm a {str1}"
print(str2)  # I'm a Python Programming

20. Find Substring

programmers = [
    "I'm an expert Python Programmer",
    "I'm an expert Javascript Programmer",
    "I'm a professional Python Programmer",
    "I'm a beginner C++ Programmer"
]
# method 1
for p in programmers:
    if p.find("Python") != -1:
        print(p)
# method 2
for p in programmers:
    if "Python" in p:
        print(p)

21. Print on the Same Line

import sys
sys.stdout.write("Call of duty ")
sys.stdout.write("and Black Ops")
# Output: Call of duty and Black Ops

print("Python ", end="")
print("Programming")
# Output: Python Programming

22. Chunk a List

def chunk(my_list, size):
    return [my_list[i:i+size] for i in range(0, len(my_list), size)]

my_list = [1, 2, 3, 4, 5, 6]
print(chunk(my_list, 2))  # [[1, 2], [3, 4], [5, 6]]

These 22 snippets aim to boost your productivity and help you write cleaner Python code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonProgrammingcode snippetsbasicsutilitiesTips
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.