22 Useful Python Code Examples: A Comprehensive Guide

Alexandr

Hatched by Alexandr

Mar 13, 2024

5 min read

0

22 Useful Python Code Examples: A Comprehensive Guide

Python is undoubtedly one of the most popular programming languages, known for its versatility and ability to solve everyday problems. In this article, we will explore 22 useful code examples that harness the power of Python. Some of these examples may be familiar to you, while others will introduce new and interesting concepts. Let's dive in and discover the potential of Python!

  1. Finding Vowels
    This code example returns all the vowels in a given string. It can be helpful when searching for or detecting vowels within a text.
def get_vowels(string):  
    return [each for each in string if each in "aeiou"]  
  
get_vowels("animal")  [a, i, a]  
get_vowels("sky")  []  
get_vowels("football")  [o, o, a]  
  1. Capitalizing the First Letter
    This example capitalizes the first letter of each word in a given string. It is useful for text analysis, data recording, and file manipulation.
def capitalize(string):  
    return string.title()  
  
capitalize("shop")  [Shop]  
capitalize("python programming")  [Python Programming]  
capitalize("how are you!")  [How Are You!]  
  1. Printing a String N Times
    This code snippet allows you to print a given string N times without using loops in Python.
n = 5  
string = "Hello World"  
print(string * n)  
 Output: Hello World Hello World Hello World Hello World Hello World  
  1. Merging Two Dictionaries
    This code example merges two dictionaries into one.
def merge(dic1, dic2):  
    dic3 = dic1.copy()  
    dic3.update(dic2)  
    return dic3  
  
dic1 = {1: "hello", 2: "world"}  
dic2 = {3: "Python", 4: "Programming"}  
merge(dic1, dic2)  {1: 'hello', 2: 'world', 3: 'Python', 4: 'Programming'}  
  1. Calculating Execution Time
    This code snippet is useful when you need to measure the time taken to execute a program or function.
import time  
  
start_time = time.time()  
  
def fun():  
    a = 2  
    b = 3  
    c = a + b  
  
end_time = time.time()  
  
fun()  
timetaken = end_time - start_time  
print("Your program takes:", timetaken)  
 Output: 0.0345  
  1. Swapping Variable Values
    This is a quick way to swap the values of two variables without using a third variable.
a = 3  
b = 4  
a, b = b, a  
print(a, b)  
 Output: a=4, b=3  
  1. Checking for Duplicates
    This code snippet provides the fastest way to check for duplicate values in a list.
def check_duplicate(lst):  
    return len(lst) != len(set(lst))  
  
check_duplicate([1,2,3,4,5,4,6])  True  
check_duplicate([1,2,3])  False  
check_duplicate([1,2,3,4,9])  False  
  1. Filtering False Values
    This example is used to remove all false values (such as False, 0, None, and "") from a list.
def Filtering(lst):  
    return list(filter(None, lst))  
  
lst = [None, 1, 3, 0, "", 5, 7]  
Filtering(lst)  [1, 3, 5, 7]  
  1. Byte Size of a String
    This code snippet returns the length of a string in bytes, which is useful when determining the size of a string variable.
def ByteSize(string):  
    return len(string.encode("utf8"))  
  
ByteSize("Python")  6  
ByteSize("Data")  4  
  1. Memory Occupied by Variables
    This example allows you to retrieve the memory usage of any variable in Python.
import sys  
  
var1 = "Python"  
var2 = 100  
var3 = True  
  
print(sys.getsizeof(var1))  55  
print(sys.getsizeof(var2))  28  
print(sys.getsizeof(var3))  28  
  1. Checking for Anagrams
    This code snippet is useful for checking if a string is an anagram. An anagram is a word formed by rearranging the letters of another word.
from collections import Counter  
  
def anagrams(str1, str2):  
    return Counter(str1) == Counter(str2)  
  
anagrams("abc1", "1bac")  True  
  1. Sorting a List
    This example sorts a list. Sorting is a commonly used task that can be accomplished with a few lines of code using Python's built-in sorting method.
my_list = ["leaf", "cherry", "fish"]  
my_list1 = ["D", "C", "B", "A"]  
my_list2 = [1, 2, 3, 4, 5]  
  
my_list.sort()  ['cherry', 'fish', 'leaf']  
my_list1.sort()  ['A', 'B', 'C', 'D']  
print(sorted(my_list2, reverse=True))  [5, 4, 3, 2, 1]  
  1. Sorting a Dictionary
    This code snippet sorts a dictionary based on its values.
orders = {  
    'pizza': 200,  
    'burger': 56,  
    'pepsi': 25,  
    'Coffee': 14  
}  
  
sorted_dic = sorted(orders.items(), key=lambda x: x[1])  
print(sorted_dic)  
 Output: [('Coffee', 14), ('pepsi', 25), ('burger', 56), ('pizza', 200)]  
  1. Getting the Last Element of a List
    This example demonstrates two ways to retrieve the last element of a list.
my_list = ["Python", "JavaScript", "C++", "Java", "C", "Dart"]  
  
 Method 1  
print(my_list[-1])  Dart  
  
 Method 2  
print(my_list.pop())  Dart  
  1. Converting a Comma-Separated List to a String
    This code snippet converts a comma-separated list into a single string. It is useful when you need to concatenate the entire list with a string.
my_list1 = ["Python", "JavaScript", "C++"]  
my_list2 = ["Java", "Flutter", "Swift"]  
  
 Example 1  
print("My favourite Programming Languages are", ", ".join(my_list1))  
 Output: My favourite Programming Languages are Python, JavaScript, C++  
  
print(", ".join(my_list2))  
 Output: Java, Flutter, Swift  
  1. Checking for Palindromes
    This code example demonstrates a quick way to check for palindromes.
def palindrome(data):  
    return data == data[::-1]  
  
palindrome("level")  True  
palindrome("madaa")  False  
  1. Shuffling a List
    This code snippet shuffles the elements of a list randomly.
from random import shuffle  
  
my_list1 = [1, 2, 3, 4, 5, 6]  
my_list2 = ["A", "B", "C", "D"]  
  
shuffle(my_list1)  [4, 6, 1, 3, 2, 5]  
shuffle(my_list2)  ['A', 'D', 'B', 'C']  
  1. Converting String Cases
    This example converts a string to uppercase and lowercase.
str1 = "Python Programming"  
str2 = "IM A PROGRAMMER"  
  
print(str1.upper())  PYTHON PROGRAMMING  
print(str2.lower())  im a programmer  
  1. String Formatting
    This code snippet allows you to format a string by incorporating data from variables.
 Example 1  
str1 = "Python Programming"  
str2 = "I'm a {}".format(str1)  
 Output: I'm a Python Programming  
  
 Example 2 - Another way  
str1 = "Python Programming"  
str2 = f"I'm a {str1}"  
 Output: I'm a Python Programming  
  1. Searching for Substrings
    This example will help you search for a substring within a string. It demonstrates two approaches that save you from writing excessive code.
programmers = [  
    "I'm an expert Python Programmer",  
    "I'm an expert Javascript Programmer",  
    "I'm a professional Python Programmer",  
    "I'm a beginner C++ Programmer"  
]  
  
 Method 1  
for p in programmers:  
    if p.find("Python"):  
        print(p)  
  
 Method 2  
for p in programmers:  
    if "Python" in p:  
        print(p)  
  1. Printing in a Single Line
    By default, the print function outputs each value in a new line. However, this code example demonstrates how to print multiple values on the same line without line breaks.
 Fastest way  
import sys  
  
sys.stdout.write("Call of duty ")  
sys.stdout.write("and Black Ops")  
 Output: Call of duty and Black Ops  
  
 Another way (Python 3 only)  
print("Python ", end="")  
print

Sources

← Back to Library

Hatch New Ideas with Glasp AI 🐣

Glasp AI allows you to hatch new ideas based on your curated content. Let's curate and create with Glasp AI :)

Start Hatching 🐣