12 Essential Python Code Snippets for Everyday Programming
This article presents twelve practical Python code snippets—including regular‑expression validation, list slicing, swapping without a temporary variable, f‑strings, dictionary inversion, multithreading, most‑common element detection, CSV parsing, and more—to help developers write concise, efficient code without lengthy boilerplate.
The article introduces a collection of twelve useful Python snippets that solve common programming tasks quickly and cleanly.
1. Regular Expression – Demonstrates how to validate email formats using re and a compiled pattern, printing "valid" or "Invalid" for given addresses.
<code># 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</code>2. Pro Slicing – Shows list and string slicing with start, end, and step indices.
<code># 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</code>3. Swap without Temp – Swaps two variables using tuple unpacking.
<code># Swap without Temp
i = 134
j = 431
[i, j] = [j, i]
print(i) # 431
print(j) # 134</code>4. Magic of f‑string – Compares traditional format() usage with the more concise f‑string syntax.
<code># 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)</code>5. Get Index – Retrieves an element's index in a list using the list.index() method.
<code># Get Index
x = [10, 20, 30, 40, 50]
print(x.index(10)) # 0
print(x.index(30)) # 2
print(x.index(50)) # 4</code>6. Sort List based on Another List – Sorts one list according to the ordering defined by a second list.
<code># 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']</code>7. Invert the Dictionary – Reverses key/value pairs in a dictionary using a dictionary comprehension.
<code># 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'}</code>8. Multi‑threading – Runs two functions concurrently using the threading module.
<code># 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()</code>9. Element Occur most in List – Provides two methods (simple max(set(...), key=...) and collections.Counter ) to find the most frequent element.
<code># Element Occur most in List
from collections import Counter
mylst = ["a","a","b","c","a","b","b","c","d","a"]
def occur_most1(mylst):
return max(set(mylst), key=mylst.count)
print(occur_most1(mylst)) # a
def occur_most2(mylst):
data = Counter(mylst)
return data.most_common(1)[0][0]
print(occur_most2(mylst)) # a</code>10. Split lines – Splits a multi‑line string into a list of lines using str.split("\n") .
<code># Split lines
data1 = """Hello to
Python"""
data2 = """Programming
Langauges"""
print(data1.split("\n")) # ['Hello to', 'Python']
print(data2.split("\n")) # ['Programming', ' Langauges']</code>11. Map List into Dictionary – Converts two parallel lists into a dictionary with dict(zip(k, v)) .
<code># 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}</code>12. Parse Spreadsheet – Shows how to read and write CSV files using Python's built‑in csv module without external dependencies.
<code># 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)</code>The article concludes with a brief disclaimer and links to related Python resources.
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.