22 Essential Python Code Snippets to Boost Your Everyday Programming
This article shares 22 practical Python code snippets that solve everyday programming challenges—from handling multiple inputs and enumerating items to measuring execution time and swapping values—providing clear explanations and ready‑to‑run examples for developers of all levels.
This article presents 22 useful Python code snippets that address common programming tasks, ranging from handling multiple inputs to measuring execution time.
1. Multiple space-separated inputs
Read multiple integers or a list from a single line of input.
## Taking Two Integers as input
a,b = map(int, input().split())
print("a:", a)
print("b:", b)
## Taking a List as input
arr = list(map(int, input().split()))
print("Input List:", arr)2. Access index and value simultaneously
Use enumerate() to get both the index and the value while iterating.
arr = [2,4,6,3,8,10]
for index, value in enumerate(arr):
print(f"At Index {index} The Value Is -> {value}")
'''Output
At Index 0 The Value Is -> 2
At Index 1 The Value Is -> 4
At Index 2 The Value Is -> 6
At Index 3 The Value Is -> 3
At Index 4 The Value Is -> 8
At Index 5 The Value Is -> 10
'''3. Check memory usage
Inspect the memory consumption of an object.
4. Print variable's unique ID
Use id() to obtain the unique identifier of an object.
5. Check anagrams
Determine whether two strings are anagrams by sorting their characters.
def check_anagram(first_word, second_word):
return sorted(first_word) == sorted(second_word)
print(check_anagram("silent", "listen")) # True
print(check_anagram("ginger", "danger")) # False6. Merge two dictionaries
Combine dictionaries using comprehension, unpacking, or the update method.
basic_information = {"name":["karl","Lary"],"mobile":["0134567894","0123456789"]}
academic_information = {"grade":["A","B"]}
# Dictionary comprehension
details = {key: value for data in (basic_information, academic_information) for key, value in data.items()}
print(details)
# Dictionary unpacking
details = {**basic_information, **academic_information}
print(details)
# Copy and update
details = basic_information.copy()
details.update(academic_information)
print(details)7. Check if a file exists
Use os.path.exists to verify the presence of a file.
import os.path
from os import path
def check_for_file():
print("File exists:", path.exists("data.txt"))
if __name__ == "__main__":
check_for_file()
# Output example: File exists: False8. Square numbers in a range
Compute squares of numbers from 1 to n using itertools.repeat or a list comprehension.
# METHOD 1
from itertools import repeat
n = 5
squares = list(map(pow, range(1, n+1), repeat(2)))
print(squares)
# METHOD 2
n = 6
squares = [i**2 for i in range(1, n+1)]
print(squares)
'''Output
[1, 4, 9, 16, 25]'''9. Convert two lists into a dictionary
Create a dictionary from two parallel lists using zip or comprehension.
list1 = ['karl', 'lary', 'keera']
list2 = [28934, 28935, 28936]
# Method 1: zip()
dictt0 = dict(zip(list1, list2))
# Method 2: dictionary comprehension
dictt1 = {key: value for key, value in zip(list1, list2)}
# Method 3: for loop (not recommended)
tuples = zip(list1, list2)
dictt2 = {}
for key, value in tuples:
if key in dictt2:
pass
else:
dictt2[key] = value
print(dictt0, dictt1, dictt2, sep="
")10. Sort a list of strings
Sort names using list.sort(), sorted(), or a manual bubble‑sort implementation.
list1 = ["Karl", "Larry", "Ana", "Zack"]
# Method 1: sort()
list1.sort()
# Method 2: sorted()
sorted_list = sorted(list1)
# Method 3: brute‑force (bubble sort)
size = len(list1)
for i in range(size):
for j in range(size):
if list1[i] < list1[j]:
temp = list1[i]
list1[i] = list1[j]
list1[j] = temp
print(list1)11. List comprehension with if/else
Filter data structures using conditional list comprehensions.
12. Add elements of two lists
Combine two numeric lists element‑wise using zip, map, or NumPy.
maths = [59, 64, 75, 86]
physics = [78, 98, 56, 56]
# Brute‑force
list1 = [maths[0]+physics[0], maths[1]+physics[1], maths[2]+physics[2], maths[3]+physics[3]]
# List comprehension
list1 = [x + y for x, y in zip(maths, physics)]
# Using map
import operator
all_devices = list(map(operator.add, maths, physics))
# Using NumPy
import numpy as np
list1 = np.add(maths, physics)
'''Output
[137 162 131 142]'''13. Sort a list of dictionaries
Order dictionaries by a specific key using sort() with a lambda or itemgetter.
dict1 = [
{"Name": "Karl", "Age": 25},
{"Name": "Lary", "Age": 39},
{"Name": "Nina", "Age": 35}
]
# Using sort() with lambda (by Age)
dict1.sort(key=lambda item: item.get("Age"))
# Using itemgetter (by Name)
from operator import itemgetter
f = itemgetter('Name')
dict1.sort(key=f)
# Using sorted()
dict1 = sorted(dict1, key=lambda item: item.get("Age"))
'''Output
[{'Age': 25, 'Name': 'Karl'}, {'Age': 35, 'Name': 'Nina'}, {'Age': 39, 'Name': 'Lary'}]'''14. Measure execution time
Record how long a code block runs using datetime, time, or timeit.
# METHOD 1
import datetime
start = datetime.datetime.now()
# CODE
print(datetime.datetime.now() - start)
# METHOD 2
import time
start_time = time.time()
# main()
print(f"Total Time To Execute The Code is {time.time() - start_time}")
# METHOD 3
import timeit
code = '''
[2,6,3,6,7,1,5,72,1].sort()
'''
print(timeit.timeit(stmt=code, number=1000))15. Find substring in a list of strings
Check each address for a specific substring.
addresses = ["12/45 Elm street", '34/56 Clark street', '56,77 maple street', '17/45 Elm street']
street = 'Elm street'
for i in addresses:
if street in i:
print(i)
'''output
12/45 Elm street
17/45 Elm street'''16. Format strings
Various ways to format strings: concatenation, f‑strings, join, the % operator, and format().
name = "Abhay"
age = 21
# METHOD 1: Concatenation
print("My name is " + name + ", and I am " + str(age) + " years old.")
# METHOD 2: F‑strings
print(f"My name is {name}, and I am {age} years old")
# METHOD 3: Join
print(''.join(["My name is ", name, ", and I am ", str(age), " years old"]))
# METHOD 4: % operator
print("My name is %s, and I am %d years old." % (name, age))
# METHOD 5: format()
print("My name is {}, and I am {} years old".format(name, age))17. Error handling
Use try, except, else, and finally to manage exceptions.
# Example 1
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a / b
print(c)
except:
print("Can't divide with zero")
# Example 2
try:
fileptr = open("file.txt", "r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
# Example 3
try:
fptr = open("data.txt", 'r')
try:
fptr.write("Hello World!")
finally:
fptr.close()
print("File Closed")
except:
print("Error")18. Most frequent element in a list
Find the element that appears most often in a list.
19. Calculator without if‑else
Map arithmetic operators to functions using the operator module.
import operator
action = {"+": operator.add, "-": operator.sub, "/": operator.truediv, "*": operator.mul, "**": pow}
print(action['*'](5, 5)) # 2520. Chain function calls
Call one of two functions in a single expression based on a condition.
def add(a, b):
return a + b
def sub(a, b):
return a - b
a, b = 9, 6
print((sub if a > b else add)(a, b))21. Swap values
Swap two variables without a temporary variable.
a, b = 5, 7
# Method 1
b, a = a, b
# Method 2
def swap(a, b):
return b, a
swap(a, b)22. Find duplicates
Detect duplicate values in a list.
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.
