Python Snippets

Python Code Snippets 1000+

1. Reverse a String

def reverse_string(s):
    return s[::-1]

# Example usage
print(reverse_string("Hello, World!"))  # Output: !dlroW ,olleH

Explanation: This function takes a string s and returns it reversed. The slicing method s[::-1] creates a new string that starts from the end towards the beginning.


2. Check if a Number is Prime

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

# Example usage
print(is_prime(11))  # Output: True

Explanation: This function checks if a number n is prime. It iterates from 2 to the square root of n, checking for divisibility. If any number divides n evenly, it returns False.


3. Count Vowels in a String

def count_vowels(s):
    vowels = "aeiouAEIOU"
    return sum(1 for char in s if char in vowels)

# Example usage
print(count_vowels("Hello, World!"))  # Output: 3

Explanation: This function counts the number of vowels in a string s. It uses a generator expression to iterate through the string and sums up the occurrences of vowels.


4. Flatten a Nested List

def flatten_list(nested_list):
    return [item for sublist in nested_list for item in sublist]

# Example usage
print(flatten_list([[1, 2], [3, 4], [5]]))  # Output: [1, 2, 3, 4, 5]

Explanation: This function flattens a nested list using a list comprehension. It iterates through each sublist and each item within those sublists.


5. Generate Fibonacci Sequence

def fibonacci(n):
    a, b = 0, 1
    sequence = []
    for _ in range(n):
        sequence.append(a)
        a, b = b, a + b
    return sequence

# Example usage
print(fibonacci(10))  # Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Explanation: This function generates the first n numbers in the Fibonacci sequence. It uses a loop to append the next number in the sequence to a list.


6. Find the Maximum Value in a List

def find_max(lst):
    return max(lst)

# Example usage
print(find_max([1, 2, 3, 4, 5]))  # Output: 5

Explanation: This function returns the maximum value from a list using Python’s built-in max() function.


7. Remove Duplicates from a List

def remove_duplicates(lst):
    return list(set(lst))

# Example usage
print(remove_duplicates([1, 2, 2, 3, 4, 4]))  # Output: [1, 2, 3, 4]

Explanation: This function removes duplicates from a list by converting it to a set (which inherently removes duplicates) and then back to a list.


8. Sort a Dictionary by Value

def sort_dict_by_value(d):
    return dict(sorted(d.items(), key=lambda item: item[1]))

# Example usage
print(sort_dict_by_value({'a': 3, 'b': 1, 'c': 2}))  # Output: {'b': 1, 'c': 2, 'a': 3}

Explanation: This function sorts a dictionary by its values. It uses the sorted() function with a lambda function as the key.


9. Check for Palindrome

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

# Example usage
print(is_palindrome("racecar"))  # Output: True

Explanation: This function checks if a string s is a palindrome by comparing it to its reverse.


10. Merge Two Dictionaries

def merge_dicts(dict1, dict2):
    return {**dict1, **dict2}

# Example usage
print(merge_dicts({'a': 1}, {'b': 2}))  # Output: {'a': 1, 'b': 2}

Explanation: This function merges two dictionaries using the unpacking operator **, which combines their key-value pairs.


11. Calculate Factorial

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

# Example usage
print(factorial(5))  # Output: 120

Explanation: This recursive function calculates the factorial of a number n. The base case is when n is 0, returning 1.


12. Find the Intersection of Two Lists

def list_intersection(lst1, lst2):
    return list(set(lst1) & set(lst2))

# Example usage
print(list_intersection([1, 2, 3], [2, 3, 4]))  # Output: [2, 3]

Explanation: This function finds the intersection of two lists by converting them to sets and using the intersection operator &.


13. Convert Celsius to Fahrenheit

def celsius_to_fahrenheit(celsius):
    return (celsius * 9/5) + 32

# Example usage
print(celsius_to_fahrenheit(0))  # Output: 32.0

Explanation: This function converts a temperature from Celsius to Fahrenheit using the formula ( F = C \times \frac{9}{5} + 32 ).


14. Count Occurrences of an Element in a List

def count_occurrences(lst, element):
    return lst.count(element)

# Example usage
print(count_occurrences([1, 2, 2, 3], 2))  # Output: 2

Explanation: This function counts how many times a specific element appears in a list using the count() method.


15. Generate a Random Password

import random
import string

def generate_password(length=8):
    characters = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(characters) for _ in range(length))

# Example usage
print(generate_password(12))  # Output: Random 12-character password

Explanation: This function generates a random password of a specified length using letters, digits, and punctuation. It uses the random.choice() method to select characters.


16. Find the Length of a String

def string_length(s):
    return len(s)

# Example usage
print(string_length("Hello, World!"))  # Output: 13

Explanation: This function returns the length of a string s using the built-in len() function.


17. Check if a String Contains Only Digits

def is_all_digits(s):
    return s.isdigit()

# Example usage
print(is_all_digits("12345"))  # Output: True

Explanation: This function checks if a string s contains only digits using the isdigit() method.


18. Find the Index of an Element in a List

def find_index(lst, element):
    return lst.index(element)

# Example usage
print(find_index([1, 2, 3, 4], 3))  # Output: 2

Explanation: This function returns the index of the first occurrence of element in a list using the index() method.


19. Remove Whitespace from a String

def remove_whitespace(s):
    return s.replace(" ", "")

# Example usage
print(remove_whitespace("Hello, World!"))  # Output: Hello,World!

Explanation: This function removes all whitespace from a string s using the replace() method.


20. Create a Simple Countdown Timer

import time

def countdown_timer(seconds):
    for i in range(seconds, 0, -1):
        print(i)
        time.sleep(1)
    print("Time's up!")

# Example usage
# countdown_timer(5)  # Uncomment to run

Explanation: This function creates a countdown timer that counts down from a specified number of seconds. It uses time.sleep(1) to pause for one second between counts.

Here are additional Python code snippets along with detailed explanations for each, continuing from the previous list:


21. Simple Calculator

import operator

calculator = {
    "+": operator.add,
    "-": operator.sub,
    "/": operator.truediv,
    "*": operator.mul,
    "**": pow
}

print(calculator['-'](10, 1))  # Output: 9

Explanation: This snippet creates a simple calculator using the operator module, which provides function equivalents for standard arithmetic operations. The calculator dictionary maps string representations of operators to their corresponding functions. The example demonstrates subtraction by calling the function associated with the '-' key.


22. Print the String N Times

n = 5
s = "hello"
print(s * n)

Explanation: This code snippet prints the string s repeated n times. In this case, it will output "hello" five times in a row, resulting in "hellohellohellohellohello".


23. Shuffle a List

from random import shuffle

foo = [1, 2, 3, 4]
shuffle(foo)

print(foo)  # Output: Randomly shuffled list, e.g., [1, 4, 3, 2]

Explanation: This snippet uses the shuffle function from the random module to randomly rearrange the elements of the list foo. Each time you run this code, the output will be a different random order of the list elements.


24. Set Difference

# Using set.difference() method
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.difference(y)

print(z)  # Output: {'banana', 'cherry'}

Explanation: This code demonstrates how to find the difference between two sets using the difference() method. The result z contains elements that are in set x but not in set y.

# Using '-' as a shortcut
a = {"apple", "banana", "cherry"}
b = {"google", "microsoft", "apple"}
myset = a - b

print(myset)  # Output: {'banana', 'cherry'}

Explanation: This snippet shows an alternative way to find the difference between two sets using the - operator, which is a shorthand for the difference() method.


25. Capitalize First Letters of Words

s = "hello world"

print(s.title())  # Output: Hello World

Explanation: This code uses the title() method to capitalize the first letter of each word in the string s. The output will be "Hello World".


26. Swap Values

def swap(a, b):
    return b, a

a, b = 1, 2
print(swap(a, b))  # Output: (2, 1)

Explanation: This function swaps the values of a and b and returns them as a tuple. The example shows how to call the function and print the swapped values.


27. Get Default Value for Missing Keys

d = {'a': 1, 'b': 2}

print(d.get('c', 3))  # Output: 3

Explanation: This code uses the get() method of dictionaries to retrieve the value for the key 'c'. Since 'c' does not exist in the dictionary d, it returns the default value 3.

Here are 20 more Python code snippets with detailed explanations for each, expanding your repertoire of useful functions and techniques:


28. Find the Minimum Value in a List

def find_min(lst):
    return min(lst)

# Example usage
print(find_min([5, 3, 8, 1, 4]))  # Output: 1

Explanation: This function returns the minimum value from a list using Python’s built-in min() function.


29. Generate a List of Squares

def generate_squares(n):
    return [x**2 for x in range(n)]

# Example usage
print(generate_squares(5))  # Output: [0, 1, 4, 9, 16]

Explanation: This function generates a list of squares of numbers from 0 to n-1 using a list comprehension.


30. Check if a String is an Anagram

def is_anagram(s1, s2):
    return sorted(s1) == sorted(s2)

# Example usage
print(is_anagram("listen", "silent"))  # Output: True

Explanation: This function checks if two strings are anagrams by sorting their characters and comparing the results.


31. Convert a List to a Set

def list_to_set(lst):
    return set(lst)

# Example usage
print(list_to_set([1, 2, 2, 3, 4]))  # Output: {1, 2, 3, 4}

Explanation: This function converts a list to a set, automatically removing duplicates.


32. Get the Current Date and Time

from datetime import datetime

def current_datetime():
    return datetime.now()

# Example usage
print(current_datetime())  # Output: Current date and time

Explanation: This function returns the current date and time using the datetime module.


33. Find the Length of a List

def list_length(lst):
    return len(lst)

# Example usage
print(list_length([1, 2, 3, 4, 5]))  # Output: 5

Explanation: This function returns the number of elements in a list using the built-in len() function.


34. Remove an Element from a List

def remove_element(lst, element):
    lst.remove(element)
    return lst

# Example usage
print(remove_element([1, 2, 3, 4], 3))  # Output: [1, 2, 4]

Explanation: This function removes the first occurrence of element from the list lst using the remove() method.


35. Check if a Number is Even

def is_even(n):
    return n % 2 == 0

# Example usage
print(is_even(4))  # Output: True

Explanation: This function checks if a number n is even by checking if the remainder when divided by 2 is zero.


36. Convert a List of Strings to Uppercase

def to_uppercase(lst):
    return [s.upper() for s in lst]

# Example usage
print(to_uppercase(["hello", "world"]))  # Output: ['HELLO', 'WORLD']

Explanation: This function converts each string in the list lst to uppercase using a list comprehension and the upper() method.


37. Check if a String Contains a Substring

def contains_substring(s, substring):
    return substring in s

# Example usage
print(contains_substring("Hello, World!", "World"))  # Output: True

Explanation: This function checks if a string s contains a specified substring using the in operator.


38. Calculate the Sum of a List

def sum_of_list(lst):
    return sum(lst)

# Example usage
print(sum_of_list([1, 2, 3, 4]))  # Output: 10

Explanation: This function calculates the sum of all elements in a list using the built-in sum() function.


39. Create a Dictionary from Two Lists

def lists_to_dict(keys, values):
    return dict(zip(keys, values))

# Example usage
print(lists_to_dict(['a', 'b', 'c'], [1, 2, 3]))  # Output: {'a': 1, 'b': 2, 'c': 3}

Explanation: This function creates a dictionary by zipping together two lists, one for keys and one for values.


40. Check if a Year is a Leap Year

def is_leap_year(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

# Example usage
print(is_leap_year(2024))  # Output: True

Explanation: This function checks if a given year is a leap year based on the rules of the Gregorian calendar.


41. Find the GCD of Two Numbers

import math

def gcd(a, b):
    return math.gcd(a, b)

# Example usage
print(gcd(12, 15))  # Output: 3

Explanation: This function calculates the greatest common divisor (GCD) of two numbers using the gcd() function from the math module.


42. Create a List of Even Numbers

def even_numbers(n):
    return [x for x in range(n) if x % 2 == 0]

# Example usage
print(even_numbers(10))  # Output: [0, 2, 4, 6, 8]

Explanation: This function generates a list of even numbers from 0 to n-1 using a list comprehension.


43. Replace a Substring in a String

def replace_substring(s, old, new):
    return s.replace(old, new)

# Example usage
print(replace_substring("Hello, World!", "World", "Python"))  # Output: Hello, Python!

Explanation: This function replaces occurrences of old substring with new in the string s using the replace() method.


44. Capitalize the First Letter of a String

def capitalize_first_letter(s):
    return s.capitalize()

# Example usage
print(capitalize_first_letter("hello"))  # Output: Hello

Explanation: This function capitalizes the first letter of the string s using the capitalize() method.


45. Merge Two Lists

def merge_lists(lst1, lst2):
    return lst1 + lst2

# Example usage
print(merge_lists([1, 2], [3, 4]))  # Output: [1, 2, 3, 4]

Explanation: This function merges two lists by concatenating them using the + operator.


46. Check if a String is Numeric

def is_numeric(s):
    return s.isnumeric()

# Example usage
print(is_numeric("12345"))  # Output: True

Explanation: This function checks if a string s consists only of numeric characters using the isnumeric() method.


47. Find the Product of a List

from functools import reduce

def product_of_list(lst):
    return reduce(lambda x, y: x * y, lst)

# Example usage
print(product_of_list([1, 2, 3, 4]))  # Output: 24

Explanation: This function calculates the product of all elements in a list using reduce() from the functools module with a lambda function.


48. Count Words in a String

def count_words(s):
    return len(s.split())

# Example usage
print(count_words("Hello, World!"))  # Output: 2

Explanation: This function counts the number of words in a string s by splitting it into a list of words and counting the length of that list.


49. Flatten a List of Lists Using Recursion

def flatten(nested_list):
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            flat_list.extend(flatten(item))
        else:
            flat_list.append(item)
    return flat_list

# Example usage
print(flatten([[1, 2], [3, [4, 5]], 6]))  # Output: [1, 2, 3, 4, 5, 6]

Explanation: This recursive function flattens a list of lists, handling any level of nesting.


50. Create a Simple GUI with Tkinter

import tkinter as tk

def on_button_click():
    print("Button clicked!")

root = tk.Tk()
button = tk.Button(root, text="Click Me", command=on_button_click)
button.pack()

root.mainloop()

Explanation: This code creates a simple graphical user interface (GUI) using the tkinter module. When the button is clicked, it executes the on_button_click() function, which prints a message to the console.


51 Contains Duplicate

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        st = set()
        for n in nums:
            if n in st:
                return True
            st.add(n)
        return False

Explanation: This code defines a method containsDuplicate which determines if there are any duplicate values in a list of integers. Here’s a breakdown of how it works:


52 Sorting a string

Sorting a string in Python involves arranging its characters in a specific order, typically in alphabetical order. Here are a few methods to achieve this:

Using sorted() Function
The sorted() function returns a sorted list of the string’s characters. You can then join these characters back into a string using join(). Here’s how you can do it:

s = "example"
sorted_string = ''.join(sorted(s))
print(sorted_string)  # Output: aeelmpx

Sorting with Case Insensitivity
If you want to sort the string in a case-insensitive manner, you can use the key parameter with str.lower or str.upper:

s = "Example"
sorted_string = ''.join(sorted(s, key=str.lower))
print(sorted_string)  # Output: aeElmpx

Reverse Sorting
To sort the string in descending order, you can use the reverse parameter:

s = "example"
sorted_string = ''.join(sorted(s, reverse=True))
print(sorted_string)  # Output: xpmleea

Print Binary

def print_binary(num):
        """
        Print the binary representation of an integer (32-bit).
        The left side is the higher bits, and the right side is the lower bits.
        """
        for i in range(31, -1, -1):
            # This line can be written as:
            # print("1" if (num & (1 << i)) != 0 else "0", end="")
            # But it cannot be written as:
            # print("1" if (num & (1 << i)) == 1 else "0", end="")
            # Because if the i-th bit of num is 1, then (num & (1 << i)) is 2^i, not necessarily 1.
            # For example, num = 0010011
            # The 0th, 1st, and 4th bits of num are 1.
            # (num & (1 << 4)) == 16 (not 1), indicating that the 4th bit of num is 1.
            print("0" if (num & (1 << i)) == 0 else "1", end="")
        print()

These methods utilize Python’s built-in functions to efficiently sort the characters in a string, allowing you to easily customize the order based on your requirements.