22 Useful Python Code Examples: Tips and Tricks for Programmers
Hatched by Alexandr
Apr 12, 2024
5 min read
12 views
22 Useful Python Code Examples: Tips and Tricks for Programmers
Python is 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 may introduce new and interesting concepts. All of these examples are easy to understand and remember, making them valuable tools for any Python programmer.
- Getting the Vowels
This code example returns all the vowels found in a given string. It can be useful when searching for or detecting vowels in a text.
def get_vowels(string):
return [each for each in string if each in "aeiou"]
print(get_vowels("animal")) Output: ['a', 'i', 'a']
print(get_vowels("sky")) Output: []
print(get_vowels("football")) Output: ['o', 'o', 'a']
- Capitalizing the First Letter
This code example converts the first letter of each word in a string to uppercase. It can be helpful when analyzing text or writing data to a file.
def capitalize(string):
return string.title()
print(capitalize("shop")) Output: Shop
print(capitalize("python programming")) Output: Python Programming
print(capitalize("how are you!")) Output: How Are You!
- Printing a String N Times
This code example can print any 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
- 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"}
print(merge(dic1, dic2)) Output: {1: 'hello', 2: 'world', 3: 'Python', 4: 'Programming'}
- Calculating Execution Time
This code example is useful when you need to know how long it takes 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
- Swapping Variable Values
This code example demonstrates 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
- Checking for Duplicates
This code example is the fastest way to check for duplicate values in a list.
def check_duplicate(lst):
return len(lst) != len(set(lst))
print(check_duplicate([1, 2, 3, 4, 5, 4, 6])) Output: True
print(check_duplicate([1, 2, 3])) Output: False
print(check_duplicate([1, 2, 3, 4, 9])) Output: False
- Filtering False Values
This code example filters out all false values from a list, such as false, 0, None, or an empty string.
def filtering(lst):
return list(filter(None, lst))
lst = [None, 1, 3, 0, "", 5, 7]
print(filtering(lst)) Output: [1, 3, 5, 7]
- Byte Size of a String
This code example returns the length of a string in bytes, which can be useful when you need to know the size of a string variable.
def byte_size(string):
return len(string.encode("utf8"))
print(byte_size("Python")) Output: 6
print(byte_size("Data")) Output: 4
- Memory Usage
This code example allows you to get the amount of memory used by any variable in Python.
import sys
var1 = "Python"
var2 = 100
var3 = True
print(sys.getsizeof(var1)) Output: 55
print(sys.getsizeof(var2)) Output: 28
print(sys.getsizeof(var3)) Output: 28
- Anagrams
This code example 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)
print(anagrams("abc1", "1bac")) Output: True
- Sorting a List
This code example sorts a list. Sorting is a common task that can be accomplished with a few lines of code using loops, but it can be made faster using the built-in sort method.
my_list = ["leaf", "cherry", "fish"]
my_list1 = ["D", "C", "B", "A"]
my_list2 = [1, 2, 3, 4, 5]
my_list.sort() Output: ['cherry', 'fish', 'leaf']
my_list1.sort() Output: ['A', 'B', 'C', 'D']
print(sorted(my_list2, reverse=True)) Output: [5, 4, 3, 2, 1]
- Sorting a Dictionary
This code example 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)]
- Getting the Last Element of a List
This code example retrieves the last element of a list in two different ways.
my_list = ["Python", "JavaScript", "C++", "Java", "C", "Dart"]
Method 1
print(my_list[-1]) Output: Dart
Method 2
print(my_list.pop()) Output: Dart
- Converting a Comma-Separated List to a String
This code example converts a comma-separated list into a single string. It is handy when you need to combine the entire list with a string.
my_list1 = ["Python", "JavaScript", "C++"]
my_list2 = ["Java", "Flutter", "Swift"]
Example 1
print("My favorite Programming Languages are", ", ".join(my_list1))
Output: My favorite Programming Languages are Python, JavaScript, C++
Example 2
print(", ".join(my_list2))
Output: Java, Flutter, Swift
- Checking for Palindromes
This code example quickly checks for the presence of palindromes.
def palindrome(data):
return data == data[::-1]
print(palindrome("level")) Output: True
print(palindrome("madaa")) Output: False
- Shuffling a List
This code example shuffles the elements of a list.
from random import shuffle
my_list1 = [1, 2, 3, 4, 5, 6]
my_list2 = ["A", "B", "C", "D"]
shuffle(my_list1) Output: [4, 6, 1, 3, 2, 5]
shuffle(my_list2) Output: ['A', 'D', 'B', 'C']
- Converting String Case
This code example converts a string to uppercase or lowercase.
str1 = "Python Programming"
str2 = "IM A PROGRAMMER"
print(str1.upper()) Output: PYTHON PROGRAMMING
print(str2.lower()) Output: im a programmer
- String Formatting
This code example allows you to format a string by adding data from variables. String formatting in Python involves appending data to a string.
Example 1
str1 = "Python Programming"
str2 = "I'm a {}".format(str1)
print(str2) Output: I'm a Python Programming
Example 2 (another way)
str1 = "Python Programming"
str2 = f"I'm a {str1}"
print(str2) Output: I'm a Python Programming
20. Searching for Substrings
This code example will help you search for a substring within a string. It demonstrates two methods that require less code.
```python
programmers = [
"I'm an expert Python Programmer",
"
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 🐣