30 Python Code Snippets for your Everyday Use

Ayushi Trivedi Last Updated : 08 Oct, 2024
10 min read

Introduction

Python is widely used by developers since it is an easy language to learn and implement. One its strong sides is that there are many samples of useful and concise code that may help to solve definite problems. Regardless of whether you are dealing with files, data, or web scraping these snippets will help you save half of the time you would have devoted to typing code. Here we will discuss 30 Python code by explaining them in detail so that you can solve day to day programming problems effectively.

30 Python Code Snippets for Your Everyday Use

Learning Outcomes

  • Learn to implement common Python code snippets for everyday tasks.
  • Understand key Python concepts such as file handling, string manipulation, and data processing.
  • Become familiar with efficient Python techniques like list comprehensions, lambda functions, and dictionary operations.
  • Gain confidence in writing clean, reusable code for solving common problems quickly.

Why You Should Use Python Code Snippets

Every programmer knows that Python code snippets are effective in any project. This way of smoothly integrating new elements arrives from instantly applying pre-written code block templates for different tasks. Snippets help you to concentrate on certain project aspects without typing monotonous code line by line. They are most valuable for use cases like list processing, file I/O, and string formatting—things you are going to do with near certainty in almost any project that you’ll write using Python.

In addition, snippets are useful in that you can refer to them as you write your code, thus preventing the mistakes that accrue from writing similar basic code over and over. That is why, having learned and repeated snippets, it is possible to achieve the construction of applications that are cleaner, more sparing of system resources, and more robust.

30 Python Code Snippets for Your Everyday Use

Let us explore 30 python code snippets for your everyday use below:

Reading a File Line by Line

This snippet opens a file and reads it line by line using a for loop. The with statement ensures the file is properly closed after reading. strip() removes any extra whitespace or newline characters from each line.

with open('filename.txt', 'r') as file:
    for line in file:
        print(line.strip())

Writing to a File

We open a file for writing using the w mode. If the file doesn’t exist, Python creates it. The write() method adds content to the file. This approach is efficient for logging or writing structured output.

with open('output.txt', 'w') as file:
    file.write('Hello, World!')

List Comprehension for Filtering

This snippet makes the use of list comprehension where a new list is created with only even numbers. The condition n % 2 == 0 looks for even numbers and Python creates a new list containing those numbers.

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [n for n in numbers if n % 2 == 0]
print(even_numbers)

Lambda Function for Quick Math Operations

Lambda functions are those function which are defined as inline functions using the lambda keyword. In this example, a full function is not defined and a lambda function simply adds two numbers instantly.

add = lambda x, y: x + y
print(add(5, 3))

Reversing a String

This snippet reverses a string using slicing. The [::-1] syntax slices the string with a step of -1, meaning it starts from the end and moves backward.

string = "Python"
reversed_string = string[::-1]
print(reversed_string)

Merging Two Dictionaries

We merge two dictionaries using the ** unpacking operator. This method is clean and efficient, particularly for modern Python versions (3.5+).

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print(merged_dict)

Sorting a List of Tuples

The following snippet sorts the given list of tuples with the help of dictionary key function set to lambda function. In particular, the sorted() function sort a list in ascending or in descending order, in accordance with the parameter passed to it; the new list was created for new sorted values.

tuples = [(2, 'banana'), (1, 'apple'), (3, 'cherry')]
sorted_tuples = sorted(tuples, key=lambda x: x[0])
print(sorted_tuples)

Fibonacci Sequence Generator

The generator function yields the first n numbers in the Fibonacci sequence. Generators are memory-efficient as they produce items on the fly rather than storing the entire sequence in memory.

def fibonacci(n):
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for num in fibonacci(10):
    print(num)

Check for Prime Number

In this snippet it is counting that if the number is a prime number using for loop from 2 to number square root. This being the case the number can be divided by any of the numbers in this range, then the number is not prime.

def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

print(is_prime(29))

Remove Duplicates from a List

Most programming languages have a built-in function to convert a list into a set by which you eliminate duplicates because sets cannot let two items be the same. Finally, the result is converted back to list from the iterable that is obtained from using the count function.

items = [1, 2, 2, 3, 4, 4, 5]
unique_items = list(set(items))
print(unique_items)

Simple Web Scraper with requests and BeautifulSoup

This web scraper uses Python’s ‘requests library’ the retrieves the page and BeautifulSoup to analyze the returned HTML. It also extracts the title of the page and prints it.

import requests
from bs4 import BeautifulSoup

response = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.text)

Convert List to String

The join() method combines elements in a list in to form a string that is delimited by a particular string (in our case it is ‘, ‘).

items = ['apple', 'banana', 'cherry']
result = ', '.join(items)
print(result)

Get Current Date and Time

The datetime.now() function return current date and time. The strftime() method formats it into a readable string format (YYYY-MM-DD HH:MM:SS).

from datetime import datetime

now = datetime.now()
print(now.strftime('%Y-%m-%d %H:%M:%S'))

Random Number Generation

This snippet generates a random integer between 1 and 100 using the random.randint() function, useful in scenarios like simulations, games, or testing.

import random

print(random.randint(1, 100))

Flatten a List of Lists

List comprehension flattens a list of lists by iterating through each sublist and extracting the elements into a single list.

list_of_lists = [[1, 2], [3, 4], [5, 6]]
flattened = [item for sublist in list_of_lists for item in sublist]
print(flattened)

Calculate Factorial Using Recursion

Recursive function calculates the factorial of a number by calling itself. It terminates when n equals zero, returning 1 (the base case).

def factorial(n):
    return 1 if n == 0 else n * factorial(n - 1)

print(factorial(5))

Swap Two Variables

Python trick enables you to interchange the values stored in two variables without using a third or temporar‌​y variable. It’s a simple one-liner.

a, b = 5, 10
a, b = b, a
print(a, b)

Remove Whitespace from String

The strip() is the standard method that, when called, strips all whitespaces that appear before and after a string. It is helpful when one wants to tidy up their input data before analysis.

text = "   Hello, World!   "
cleaned_text = text.strip()
print(cleaned_text)

Find the Maximum Element in a List

The max() function locate and return the biggest value within a given list. It is an effective method to get the maximum of list of numbers, because it is fast.

numbers = [10, 20, 30, 40, 50]
max_value = max(numbers)
print(max_value)

Check If a String is Palindrome

This snippet checks if a string is a palindrome by comparing the string to its reverse ([::-1]), returning True if they are identical.

def is_palindrome(string):
    return string == string[::-1]

print(is_palindrome('madam'))

Count Occurrences of an Element in a List

The count() method returns the number of times an element appears in a list. In this example, it counts how many times the number 3 appears.

items = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
count = items.count(3)
print(count)

Create a Dictionary from Two Lists

The zip() function pairs elements from two lists into tuples, and the dict() constructor converts these tuples into a dictionary. It’s a simple way to map keys to values.

keys = ['name', 'age', 'job']
values = ['John', 28, 'Developer']
dictionary = dict(zip(keys, values))
print(dictionary)

Shuffle a List

This snippet shuffles a list in place using the random.shuffle() method, which randomly reorders the list’s elements.

import random

items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items)

Filter Elements Using filter()

Filter() function works on a list and takes a condition that can be a lambda function in this case then it will return only those elements of the list for which the condition is true (all the even numbers here).

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)

Measure Execution Time of a Code Block

This snippet measures the execution time of a block of code using time.time(), which returns the current time in seconds. This is useful for optimizing performance.

import time

start_time = time.time()
# Some code block
end_time = time.time()
print(f"Execution Time: {end_time - start_time} seconds")

Convert Dictionary to JSON

The json.dumps() function take Python dictionary and returns JSON formatted string. This is especially useful when it comes to making API requests or when storing information in a JSON object.

import json

data = {'name': 'John', 'age': 30}
json_data = json.dumps(data)
print(json_data)

Check If a Key Exists in a Dictionary

This snippet checks if a key exists in a dictionary using the in keyword. If the key is found, it executes the code in the if block.

person = {'name': 'Alice', 'age': 25}
if 'name' in person:
    print('Key exists')

Zip Multiple Lists

The zip() function combines multiple lists by pairing elements with the same index. This can be useful for creating structured data from multiple lists.

names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
zipped = list(zip(names, ages))
print(zipped)

Generate List of Numbers Using range()

The range() function generates a sequence of numbers, which is converted into a list using list(). In this example, it generates numbers from 1 to 10.

numbers = list(range(1, 11))
print(numbers)

Check If a List is Empty

This snippet checks if a list is empty by using not. If the list contains no elements, the condition evaluates to True.

items = []
if not items:
    print("List is empty")

Best Practices for Reusing Code Snippets

When reusing code snippets, following a few best practices will help ensure that your projects maintain quality and efficiency:

  • Understand Before Using: Avoid blindly copying snippets. Take the time to understand how each snippet works, its inputs, and its outputs. This will help you avoid unintended bugs.
  • Test in Isolation: Test snippets in isolation to ensure they perform as expected. It’s essential to verify that the snippet works correctly in the context of your project.
  • Comment and Document: When modifying a snippet for your needs, always add comments. Documenting changes will help you or other developers understand the logic later on.
  • Follow Coding Standards: Ensure that snippets adhere to your coding standards. They should be written clearly and follow conventions like proper variable naming and formatting.
  • Adapt to Your Use Case: Don’t hesitate to adapt a snippet to fit your specific project needs. Modify it to ensure it works optimally with your codebase.

Tools for Managing Your Own Snippet Library

Creating a personal library of Python code snippets is useful and can eliminate the need to search for codes in other project. Several tools are available to help you store, organize, and quickly access your snippets:

  • GitHub Gists: Through use of Gists, GitHub provides an exemplary way of storing and sharing snippets of code effortlessly. These snippets can be either public or private in nature which makes it can be accessed from any location and device.
  • VS Code Snippets: Visual Studio Code also integrated a powerful snippet manager in which you can create your own snippet sets with assignable shortcuts to be utilized across diverse projects. It also gives snippets the ability to categorize them by language.
  • SnipperApp: For Mac users, SnipperApp provides an intuitive interface to manage and categorize your code snippets, making them searchable and easily accessible when needed.
  • Sublime Text Snippets: Moreover, Sublime Text also gives you the option to master and even customize the snippets built-in your development environment.
  • Snippet Manager for Windows: This tool can assist developers on windows platforms to categorize, tag, and search for snippets easily.

Tips for Optimizing Snippets for Performance

While code snippets help streamline development, it’s important to ensure that they are optimized for performance. Here are some tips to keep your snippets fast and efficient:

  • Minimize Loops: If this is possible, eliminate loops and use list comprehensions which are faster in Python.
  • Use Built-in Functions: Python attached functions, sum(), max() or min(), are written in C and are usually faster than those implemented by hand.
  • Avoid Global Variables: I also came across some special issues when developing snippets, one of which is the usage of global variables, which results in performance problems. Rather try to use local variables or to pass the variables as parameters.
  • Efficient Data Structures: When retrieving records it important take the right structure to complete the task. For instance, use sets to make sure that membership check is done in a short time while using dictionaries to obtain quick lookups.
  • Benchmark Your Snippets: Time your snippets and use debugging and profiling tools and if possible use time it to show you the bottlenecks. It helps in making sure that your code is not only correct but also correct in terms of, how fast it can execute on your computer.

Common Mistakes to Avoid When Using Python Snippets

While code snippets can save time, there are common mistakes that developers should avoid when reusing them:

  • Copy-Pasting Without Understanding: One fault was mentioned to be especially devastating – that of lifting the code and not really knowing what one does. This results in an erroneous solution when the snippet is then taken and applied in a new setting.
  • Ignoring Edge Cases: Snippets are good for a general case when the typical values are entered, but they do not consider special cases (for example, an empty field, but there may be a large number of other values). When you write your snippets, always try to run them with different inputs.
  • Overusing Snippets: Still, if one uses snippets a lot, he/she will never really get the language and just be a Outsource Monkey, using translation software on daily basis. Try to find out how the snippets are implemented.
  • Not Refactoring for Specific Needs: As one might guess from their name, snippets are intended to be flexible. If a snippet is not customized to fit the specific project it is being used on, then there is a high possibility that the project will experience some inefficiencies, or bugs it.
  • Not Checking for Compatibility: Ensure that the snippet you’re using is compatible with the version of Python you’re working with. Some snippets may use features or libraries that are deprecated or version-specific.

Conclusion

These 30 Python code snippets cover a wide array of common tasks and challenges that developers face in their day-to-day coding. From handling files, and working with strings, to web scraping and data processing, these snippets save time and simplify coding efforts. Keep these snippets in your toolkit, modify them for your needs, and apply them in real-world projects to become a more efficient Python developer.

If you want to learn python for free, here is our introduction to python course!

Frequently Asked Questions

Q1. How can I learn more about Python beyond these snippets?

A. Practice regularly, explore Python documentation, and contribute to projects on GitHub.

Q2. Are these snippets suitable for beginners?

A. Yes, they are easy to understand and helpful for beginners as well as experienced developers.

Q3. How can I remember these code snippets?

A. Practice by using them in real-world projects. Repetition will help you recall them easily.

Q4. Can I modify these snippets for more complex tasks?

A. Absolutely! These snippets provide a solid foundation, but you can build more complex logic around them based on your needs.

My name is Ayushi Trivedi. I am a B. Tech graduate. I have 3 years of experience working as an educator and content editor. I have worked with various python libraries, like numpy, pandas, seaborn, matplotlib, scikit, imblearn, linear regression and many more. I am also an author. My first book named #turning25 has been published and is available on amazon and flipkart. Here, I am technical content editor at Analytics Vidhya. I feel proud and happy to be AVian. I have a great team to work with. I love building the bridge between the technology and the learner.

Responses From Readers

Clear

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details