# Unleashing the Power of Python: 22 Practical Code Examples
Hatched by Alexandr
Jan 22, 2025
5 min read
6 views
Unleashing the Power of Python: 22 Practical Code Examples
Python has become one of the most popular programming languages in recent years. Its simplicity, versatility, and vast libraries make it an ideal choice for both beginners and experienced developers. Whether you're automating mundane tasks, analyzing data, or developing complex applications, Python offers solutions that can streamline your workflow. In this article, we will explore 22 practical code examples that demonstrate the power of Python in everyday programming tasks.
- Extracting Vowels from a String
One of the simplest yet useful tasks is extracting vowels from a string. This can help in various text analysis applications.
def get_vowels(string):
return [char for char in string if char in "aeiou"]
print(get_vowels("animal")) Output: ['a', 'i', 'a']
- Capitalizing the First Letter of Each Word
This function can be particularly useful in preparing text for display or output.
def capitalize(string):
return string.title()
print(capitalize("python programming")) Output: 'Python Programming'
- Printing a String Multiple Times
Sometimes you need to repeat a string without looping. This can be achieved succinctly.
n = 5
string = "Hello World "
print(string * n)
- Merging Two Dictionaries
This example highlights how to combine two dictionaries effortlessly.
def merge(dic1, dic2):
dic3 = dic1.copy()
dic3.update(dic2)
return dic3
dic1 = {1: "hello", 2: "world"}
dic2 = {3: "Python", 4: "Programming"}
print(merge(dic1, dic2)) Output: {1: 'hello', 2: 'world', 3: 'Python', 4: 'Programming'}
- Measuring Execution Time
Knowing how long your code takes to run can be crucial for optimization.
import time
start_time = time.time()
def fun():
a = 2
b = 3
return a + b
fun()
end_time = time.time()
print("Your program takes: ", end_time - start_time)
- Swapping Variable Values
This code allows you to swap two variables without a temporary variable, showcasing Python's elegant syntax.
a, b = 3, 4
a, b = b, a
print(a, b) Output: 4, 3
- Checking for Duplicates in a List
This is a handy function for ensuring data integrity.
def check_duplicate(lst):
return len(lst) != len(set(lst))
print(check_duplicate([1, 2, 3, 4, 5, 4])) Output: True
- Filtering Out False Values
This function can clean up lists by removing any falsy values.
def filtering(lst):
return list(filter(None, lst))
lst = [None, 1, 3, 0, "", 5, 7]
print(filtering(lst)) Output: [1, 3, 5, 7]
- Getting the Byte Size of a String
Understanding the memory size of your strings can be useful, especially in data-heavy applications.
def byte_size(string):
return len(string.encode("utf8"))
print(byte_size("Python")) Output: 6
- Checking Memory Size of Variables
This example shows how much memory different variable types use.
import sys
var1 = "Python"
var2 = 100
var3 = True
print(sys.getsizeof(var1)) Output: 55 (or similar)
- Checking for Anagrams
A practical function to determine if two strings are anagrams.
from collections import Counter
def anagrams(str1, str2):
return Counter(str1) == Counter(str2)
print(anagrams("abc", "cab")) Output: True
- Sorting a List
Sorting is a common task, and Python makes it easy.
my_list = ["leaf", "cherry", "fish"]
my_list.sort()
print(my_list) Output: ['cherry', 'fish', 'leaf']
- Sorting a Dictionary by Values
This can be beneficial when you want to analyze data stored in dictionaries.
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)]
- Accessing the Last Element of a List
A straightforward method to retrieve the last element without knowing the length.
my_list = ["Python", "Java", "C++"]
print(my_list[-1]) Output: 'C++'
- Joining a List into a String
This function is useful for formatting output.
my_list = ["Python", "JavaScript", "C++"]
print(", ".join(my_list)) Output: 'Python, JavaScript, C++'
- Checking for Palindromes
A quick way to check if a string reads the same forwards and backwards.
def palindrome(data):
return data == data[::-1]
print(palindrome("level")) Output: True
- Shuffling a List
Randomizing the order of elements can be important in various applications.
from random import shuffle
my_list = [1, 2, 3, 4, 5]
shuffle(my_list)
print(my_list) Output: Randomly shuffled list
- Converting Strings to Upper and Lower Case
Changing the case of strings is a frequent requirement.
str1 = "Python Programming"
print(str1.upper()) Output: 'PYTHON PROGRAMMING'
- String Formatting
Concatenating strings with variable data can enhance readability.
str1 = "Python Programming"
print(f"I'm a {str1}") Output: "I'm a Python Programming"
- Substring Searching
This functionality can be critical in text processing.
programmers = ["I'm an expert Python Programmer", "I'm a beginner C++ Programmer"]
for p in programmers:
if "Python" in p:
print(p)
- Printing in the Same Line
This shows how to control output formatting in the console.
import sys
sys.stdout.write("Hello ")
sys.stdout.write("World!") Output: Hello World!
- Chunking a List
Breaking a list into smaller parts can be useful for data processing.
def chunk(my_list, size):
return [my_list[i:i + size] for i in range(0, len(my_list), size)]
print(chunk([1, 2, 3, 4, 5, 6], 2)) Output: [[1, 2], [3, 4], [5, 6]]
Actionable Advice
- Practice Regularly: The best way to learn Python is through consistent practice. Try to solve small problems every day.
- Explore Libraries: Familiarize yourself with popular libraries like NumPy, Pandas, and Matplotlib to expand your capabilities in data analysis and visualization.
- Engage with the Community: Join Python forums and communities like Stack Overflow or Reddit. Engaging with others can provide support and insights that enhance your learning experience.
In conclusion, Python is a powerful tool that can simplify many programming tasks. The examples provided illustrate just a fraction of its capabilities. By consistently practicing and exploring its wide array of libraries, you can unlock even more potential in your programming projects. Happy coding!
Sources
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 🐣