0% found this document useful (0 votes)
2 views11 pages

Python Snippets Reference

This document provides 100 intermediate Python code snippets organized into six categories: Data Structures & Logic, Intermediate Automation & File I/O, Functional & Advanced Python, Data Processing & APIs, Utility & Security, and Quick Logic Snippets. Each snippet serves as a practical reference for common tasks and operations in Python programming. The snippets cover a wide range of topics, including data manipulation, file handling, web scraping, and more.

Uploaded by

ammykhan0000005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views11 pages

Python Snippets Reference

This document provides 100 intermediate Python code snippets organized into six categories: Data Structures & Logic, Intermediate Automation & File I/O, Functional & Advanced Python, Data Processing & APIs, Utility & Security, and Quick Logic Snippets. Each snippet serves as a practical reference for common tasks and operations in Python programming. The snippets cover a wide range of topics, including data manipulation, file handling, web scraping, and more.

Uploaded by

ammykhan0000005
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

100 Intermediate Python Code Snippets

A practical reference guide for intermediate Python developers

1. Data Structures & Logic

Find the most frequent element in a list.


1 from collections import Counter
data = [1, 2, 3, 1, 2, 1, 4]
print(Counter(data).most_common(1)[0][0])

Merge two dictionaries (Python 3.9+).


2 d1 = {'a': 1}; d2 = {'b': 2}
print(d1 | d2)

Filter a list of strings for a specific substring.


3 names = ["Tauqeer", "Ahmed", "Ishaq"]
print([n for n in names if "ee" in n])

Check if two strings are anagrams.


4 s1, s2 = "listen", "silent"
print(sorted(s1) == sorted(s2))

Get a list of unique values while preserving order.


5 items = [1, 2, 2, 3, 1]
print(list([Link](items)))

Convert a list of tuples into a dictionary.


6 pairs = [('x', 1), ('y', 2)]
print(dict(pairs))

Find the intersection of two lists.


7 l1 = [1, 2, 3]; l2 = [2, 3, 4]
print(list(set(l1) & set(l2)))

Group a list into chunks of size N.


8
nums = range(10)
print([list(nums[i:i+3]) for i in range(0, len(nums), 3)])

Reverse a dictionary (keys become values).


9 d = {'a': 1, 'b': 2}
print({v: k for k, v in [Link]()})

Find the difference between two lists.


10 l1 = [1, 2, 3]; l2 = [1, 2]
print(list(set(l1) - set(l2)))

Transpose a matrix.
11 m = [[1, 2], [3, 4]]
print([list(i) for i in zip(*m)])

Check if a list is empty.


12 items = []
print(not items)

Remove whitespace from all strings in a list.


13 s = [" apple ", "orange "]
print([[Link]() for x in s])

Create a string from a list with a separator.


14 words = ["Python", "is", "cool"]
print(" ".join(words))

Get the size of an object in bytes.


15 import sys
print([Link]("Hello"))

2. Intermediate Automation & File I/O

List all files in a directory with a specific extension.


16 import glob
print([Link]("*.csv"))

Read a specific line from a file without loading the whole file.
17
import linecache
print([Link]('[Link]', 5))

Check if a file exists.


18 import os
print([Link]('[Link]'))

Create a directory if it doesn't exist.


19 import os
[Link]('logs/daily', exist_ok=True)

Get the current timestamp in ISO format.


20 from datetime import datetime
print([Link]().isoformat())

Calculate the number of days between two dates.


21 from datetime import date
d0, d1 = date(2026, 1, 1), date(2026, 5, 15)
print((d1 - d0).days)

Parse a JSON string into a dictionary.


22 import json
print([Link]('{"id": 101}'))

Write a dictionary to a JSON file with indentation.


23 import json
with open('[Link]', 'w') as f:
[Link]({'status': 'ok'}, f, indent=2)

Zip two lists into a dictionary.


24 keys = ['name', 'age']; vals = ['Tauqeer', 28]
print(dict(zip(keys, vals)))

Flatten a nested list of lists.


25 nested = [[1, 2], [3, 4]]
print(sum(nested, []))

Generate a random string of fixed length.


26 import string, random
print(''.join([Link](string.ascii_letters, k=8)))

27 Measure time taken by a code block.


import time
start = [Link]()
# code here
print(f"Elapsed: {[Link]() - start}")

Download an image from a URL.


28 import requests
r = [Link]("[Link]
with open('[Link]', 'wb') as f: [Link]([Link])

Get environment variables.


29 import os
print([Link]('USER', 'Guest'))

Convert CSV to JSON.


30 import pandas as pd
# pd.read_csv('[Link]').to_json('[Link]')

3. Functional & Advanced Python

Use map to convert a list of strings to integers.


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

Filter out None values from a list.


32 data = [1, None, 2, None]
print(list(filter(None, data)))

Use enumerate to get index and value.


33
for i, v in enumerate(['a', 'b']): print(i, v)

Use zip to iterate over two lists simultaneously.


34
for a, b in zip([1, 2], ['x', 'y']): print(a, b)

Create a simple class with dataclasses.


from dataclasses import dataclass
35 @dataclass
class User: id: int; name: str
print(User(1, "Tauqeer"))
Use a lambda function to calculate the hypotenuse.
36 hyp = lambda a, b: (a**2 + b**2)**0.5
print(hyp(3, 4))

Implementation of a Simple Singleton.


class Singleton:
37 _instance = None
def __new__(cls):
if not cls._instance: cls._instance = super().__new__(cls)
return cls._instance

Run a shell command from Python.


38 import subprocess
[Link](["ls", "-l"])

Format numbers with commas.


39
print(f"{1000000:,}")

Get the name of the current function.


40 import inspect
print([Link]()[0][3])

Check if all elements in a list are true.


41
print(all([True, 1, "yes"]))

Check if any element in a list is true.


42
print(any([0, False, "truthy"]))

Use [Link] to avoid KeyErrors.


from collections import defaultdict
43 d = defaultdict(list)
d['new_key'].append(1)
print(d)

Sorting a list of strings by length.


44 words = ["python", "is", "awesome"]
print(sorted(words, key=len))

Create a simple CLI progress bar.


45 for i in range(11):
print(f"\rProgress: [{'#'*i}{'.'*(10-i)}]", end="")
import time; [Link](0.1)
4. Data Processing & APIs

Scrape all links from a webpage.


from bs4 import BeautifulSoup
46 import requests
res = [Link]("[Link]
soup = BeautifulSoup([Link], '[Link]')
print([a['href'] for a in soup.find_all('a', href=True)])

Convert a pandas DataFrame to an Excel file.


47 import pandas as pd
df = [Link]({'A': [1, 2]})
# df.to_excel('[Link]')

Fetch a response from a REST API.


48 import requests
print([Link]('[Link]

Generate a QR Code.
49 # requires: pip install qrcode
import qrcode
[Link]("[Link]

Simple regex to find phone numbers.


50 import re
text = "Call me at 555-123-4567"
print([Link](r'\d{3}-\d{3}-\d{4}', text))

Get public IP address.


51 import requests
print([Link]('[Link]

Create a basic Flask Web App.


from flask import Flask
52 app = Flask(__name__)
@[Link]("/")
def home(): return "Hello World"
# [Link]()

Read environment variables from a .env file.


53 # requires: pip install python-dotenv
from dotenv import load_dotenv
load_dotenv()

Calculate Euclidean distance between two points.


54 import math
print([Link]([0, 0], [3, 4]))

Merge multiple CSVs into one.


import pandas as pd
55 import glob
all_files = [Link]("*.csv")
df = [Link]((pd.read_csv(f) for f in all_files))

Send a notification to Discord via Webhook.


56 import requests
# [Link](webhook_url, json={"content": "Hello"})

Pretty print a dictionary.


57 from pprint import pprint
pprint({"a": 1, "b": {"c": 2, "d": 3}})

Base64 encode a string.


58 import base64
print(base64.b64encode(b"hello").decode())

Extract text from an image (OCR).


59 # requires: pytesseract
# from PIL import Image; import pytesseract
# print(pytesseract.image_to_string([Link]('[Link]')))

Get stock price using yfinance.


60 import yfinance as yf
print([Link]("AAPL").history(period="1d"))

5. Utility & Security

Password hashing with salt.


61 import hashlib
print(hashlib.sha256(b"password").hexdigest())
Check if a number is prime.
62 is_prime = lambda n: all(n % i != 0 for i in range(2, int(n**0.5) + 1))
and n > 1
print(is_prime(17))

Find the factorial of a number.


63 import math
print([Link](5))

Get local computer hostname.


64 import socket
print([Link]())

Create a temporary file.


65 import tempfile
with [Link]() as tmp: print([Link])

Check memory usage of the current process.


66 import psutil, os
print([Link]([Link]()).memory_info().rss)

Find all indices of an item in a list.


67 data = [1, 2, 1, 3, 1]
print([i for i, x in enumerate(data) if x == 1])

Convert binary to integer.


68
print(int('1010', 2))

Convert integer to hex.


69
print(hex(255))

Remove HTML tags from a string.


70 import re
print([Link]('<[^<]+?>', '', '<b>Hello</b>'))

Create an infinite iterator.


from itertools import count
71 for i in count(10):
if i > 12: break
print(i)
Find the most common character in a string.
72 s = "success"
print(max(s, key=[Link]))

Convert XML to Dictionary.


73 # requires: pip install xmltodict
# import xmltodict; [Link]('<root>...</root>')

Clear the terminal screen.


74 import os
[Link]('cls' if [Link] == 'nt' else 'clear')

Get current working directory.


75 import os
print([Link]())

6. Quick Logic Snippets

Check for leap year.


76 import calendar
[Link](2026)

Shuffle a list.
77 import random
l = [1, 2]
[Link](l)

Get random element.


78
[Link]([1, 2, 3])

Get file size.


79
[Link]('[Link]')

Capitalize first letter of every word.


80
"hello world".title()

Check if string is numeric.


81
"123".isnumeric()
Rotate list by N.
82
l[n:] + l[:n]

Get execution path.


83
[Link]

Repeat string N times.


84
"A" * 10

Swap two variables.


85
a, b = b, a

Check for duplicates in list.


86
len(l) != len(set(l))

Count specific element.


87
[1,1,2].count(1)

Convert list of chars to string.


88
"".join(['a','b'])

Deep copy a list.


89 import copy
[Link](l)

Get current CPU count.


90
os.cpu_count()

Convert string to datetime.


91
[Link]("2026-05-15", "%Y-%m-%d")

Get weekday of a date.


92
[Link]().strftime("%A")

Round to 2 decimal places.


93
round(3.14159, 2)
Check if key exists in Dict.
94
"key" in my_dict

Get values of a Dict.


95
my_dict.values()

Sort Dict by value.


96
dict(sorted([Link](), key=lambda x: x[1]))

Calculate percentage.
97
(part/total)*100

Get file extension.


98
[Link]('[Link]')[1]

Find GCD of two numbers.


99 import math
[Link](10, 20)

Wait for user input.


100
"Press Enter to exit"

| 100 Python Snippets | 2026

You might also like