Fundamentals 9 min read

12 Must‑Know Python Code Snippets to Boost Your Daily Development

This article presents twelve practical Python code snippets—from regular expressions and list slicing to multithreading and CSV handling—that let you solve common programming tasks quickly and efficiently without writing lengthy code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
12 Must‑Know Python Code Snippets to Boost Your Daily Development

In this article we share twelve practical Python code snippets that solve common daily programming tasks without writing lengthy code.

1. Regular Expressions

Use regular expressions to validate email formats efficiently.

# Regular Expression Check Mail
import re

def Check_Mail(email):
    pattern = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')
    if re.fullmatch(pattern, email):
        print("valid")
    else:
        print("Invalid")

Check_Mail("[email protected]")  # valid
Check_Mail("[email protected]")  # Invalid
Check_Mail("[email protected]")  # Invalid

2. Pro Slicing

Slice lists and strings like a professional using Python's extended slice syntax.

# Pro Slicing
# list[start:end:step]
mylist = [1, 2, 3, 5, 5, 6, 7, 8, 9, 12]
mail = "[email protected]"
print(mylist[4:-3])  # [5, 6, 7]
print(mail[8:14])    # medium

3. Swap without Temp

Swap two variables without a temporary placeholder.

# Swap without Temp
i = 134
j = 431
[i, j] = [j, i]
print(i)  # 431
print(j)  # 134

4. Magic of f‑String

Use f‑strings for concise and readable string formatting.

# Magic of f-String
# Normal Method
name = "Codedev"
lang = "Python"
data = "{} is writing article on {}".format(name, lang)
print(data)

# Pro Method with f-string
data = f"{name} is writing article on {lang}"
print(data)

5. Get Index

Find the index of an element in a list without looping.

# Get Index
x = [10, 20, 30, 40, 50]
print(x.index(10))  # 0
print(x.index(30))  # 2
print(x.index(50))  # 4

6. Sort List Based on Another List

Sort a list according to the ordering defined in a second list.

# Sort List based on another List
list1 = ["a","b","c","d","e","f","g","h","i","j","k","l","m"]
list2 = [0,1,1,1,2,2,0,1,1,3,4]
C = [x for _, x in sorted(zip(list2, list1), key=lambda pair: pair[0])]
print(C)  # ['a', 'g', 'b', 'c', 'd', 'h', 'i', 'e', 'f', 'j', 'k']

7. Invert the Dictionary

Reverse a dictionary's key‑value pairs without explicit loops.

# Invert the Dictionary
def Invert_Dictionary(data):
    return {value: key for key, value in data.items()}

data = {"A": 1, "B": 2, "C": 3}
invert = Invert_Dictionary(data)
print(invert)  # {1: 'A', 2: 'B', 3: 'C'}

8. Multi‑threading

Run functions concurrently using Python's threading module.

# Multi-threading
import threading

def func(num):
    for x in range(num):
        print(x)

if __name__ == "__main__":
    t1 = threading.Thread(target=func, args=(10,))
    t2 = threading.Thread(target=func, args=(20,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

9. Element Occurs Most in List

Find the most frequent element in a list using two different methods.

# Element Occur most in List
from collections import Counter
mylst = ["a","a","b","c","a","b","b","c","d","a"]

# Method 1
def occur_most1(lst):
    return max(set(lst), key=lst.count)
print(occur_most1(mylst))  # a

# Method 2 (faster)
def occur_most2(lst):
    data = Counter(lst)
    return data.most_common(1)[0][0]
print(occur_most2(mylst))  # a

10. Split Lines

Split a multi‑line string into a list of lines.

# Split lines
data1 = """Hello to
Python"""
data2 = """Programming
Langauges"""
print(data1.split("
"))  # ['Hello to', 'Python']
print(data2.split("
"))  # ['Programming', ' Langauges']

11. Map List into Dictionary

Convert two parallel lists into a dictionary.

# Map List into Dictionary
def Convert_to_Dict(k, v):
    return dict(zip(k, v))

k = ["a", "b", "c", "d", "e"]
v = [1, 2, 3, 4, 5]
print(Convert_to_Dict(k, v))  # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

12. Parse Spreadsheet (CSV)

Read and write CSV files using Python's built‑in csv module.

# Parse Spreadsheet
import csv

# Reading
with open("test.csv", "r") as file:
    csv_reader = csv.reader(file)
    for row in csv_reader:
        print(row)

# Writing
header = ["ID", "Languages"]
csv_data = [234, "Python", 344, "JavaScript", 567, "Dart"]
with open("test2.csv", "w", newline="") as file:
    csv_writer = csv.writer(file)
    csv_writer.writerow(header)
    csv_writer.writerows(csv_data)

These twelve snippets can be directly used in your projects to solve everyday development problems efficiently.

Pythonregular expressionsCSVdictionarylist slicing
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.