Top 30 Useful Python Snippets that are Useful for Your Next Project
-
Check if a string is empty:
if not my_string: print("String is empty")
-
Sort a dictionary by value:
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
-
Merge two dictionaries:
my_dict_1.update(my_dict_2)
-
Flatten a list of lists:
flattened_list = [item for sublist in my_list for item in sublist]
-
Check if a list contains duplicates:
if len(my_list) != len(set(my_list)): print("List contains duplicates")
-
Reverse a string:
reversed_string = my_string[::-1]
-
Get the current date and time:
import datetime now = datetime.datetime.now()
-
Get the file extension from a file path:
file_extension = os.path.splitext(file_path)[1]
-
Convert a string to a boolean:
my_bool = my_string.lower() in ['true', 't', 'yes', 'y', '1']
- Remove duplicates from a list while preserving order
seen = set() unique_list = [x for x in my_list if x not in seen and not seen.add(x)]
-
Convert a list of strings to a single string:
my_string = ' '.join(my_list)
-
Generate a random number:
import random random_number = random.randint(min_value, max_value)
-
Get the size of a file:
file_size = os.path.getsize(file_path)
-
Replace all occurrences of a substring in a string:
new_string = my_string.replace(substring, new_substring)
-
Get the last N elements of a list:
last_n_elements = my_list[-n:]
-
Filter a list based on a condition:
filtered_list = [x for x in my_list if condition(x)]
-
Check if a file exists:
if os.path.isfile(file_path): print("File exists")
-
Read a file line by line:
with open(file_path) as f: for line in f: print(line)
-
Get the current working directory:
current_directory = os.getcwd()
-
Create a directory if it does not exist:
if not os.path.exists(directory_path): os.makedirs(directory_path)
-
Creating a dictionary from two lists:
keys = ['a', 'b', 'c'] values = [1, 2, 3] my_dict = dict(zip(keys, values))
-
Checking if a file exists:
import os if os.path.exists('/path/to/file.txt'): # do something
-
Getting the current date and time:
from datetime import datetime now = datetime.now() current_time = now.strftime("%H:%M:%S")
-
Reversing a string:
my_string = "Hello, world!" reversed_string = my_string[::-1]
-
Generating a random number:
import random my_number = random.randint(1, 100)
-
Converting a string to a list:
my_string = "apple,banana,orange" my_list = my_string.split(",")
-
Sorting a list of dictionaries by a specific key:
my_list = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 20}] sorted_list = sorted(my_list, key=lambda x: x['age'])
-
Removing duplicates from a list:
my_list = [1, 2, 3, 2, 1] my_list = list(set(my_list))
-
Checking if a string contains a substring:
my_string = "Hello, world!" if "world" in my_string: # do something
-
Joining a list of strings into a single string:
my_list = ['apple', 'banana', 'orange'] my_string = ', '.join(my_list)
That’s all for today! Cheers!!!
You can also read my other posts in python:
- Machine Learning: Multiclass Classification Template for any Classification Dataset
- Cyber Security (in Python) Books, Codes, and other Resource Collection available on GitHub
- Write a Reverse Proxy Server in Python: Part 1 (Reverse Proxy Server)
- Add Custom Headers to Python Files in Seconds using VSCode Editor
- How to Write a RESTful API using Python Flask to fetch data from PostgreSQL Database
- Python ZeroMQ Module: A Simple Publisher-Subscriber Chat Application
- Python Logging: Basic Tutorial and Template
- Creating and Reading QR Code in Python: A Simple Python Class using
qrcode
andopencv
module - A Curated list of Python Cheatsheets Collections
- How to write a Twitter Data Scrapper in Python
- Useful Functions of Python Itertools Module
- Collection of
Data Science in Python
Posts in my Blog - Introduction to Deep Learning in Python (Keras and Tensorflow) using the MNIST Dataset
Leave a comment