20 Essential Python Tricks to Boost Your Coding Efficiency
This article showcases 20 practical Python techniques—from string reversal and title-casing to dictionary merging and execution timing—each illustrated with clear code examples, helping developers write more readable, efficient, and Pythonic code.
Python's readability and simplicity make it popular; this article presents 20 practical Python tricks to improve code readability and save development time.
String reversal
Use slicing to reverse a string:
# Reversing a string using slicing
my_string = "ABCDE"
reversed_string = my_string[::-1]
print(reversed_string) # EDCBACapitalize first letter of each word
Apply the title() method:
my_string = "my name is chaitanya baweja"
new_string = my_string.title()
print(new_string) # My Name Is Chaitanya BawejaFind unique characters in a string
Convert the string to a set and join back:
my_string = "aavvccccddddeee"
temp_set = set(my_string)
new_string = ''.join(temp_set)
print(new_string) # cdvae (order may vary)Repeat a string or list n times
Use the multiplication operator:
n = 3 # number of repetitions
my_string = "abcd"
my_list = [1, 2, 3]
print(my_string * n) # abcdabcdabcd
print(my_list * n) # [1, 2, 3, 1, 2, 3, 1, 2, 3]List comprehension to multiply each element
Multiply each element by 2 using a list comprehension:
original_list = [1, 2, 3, 4]
new_list = [2 * x for x in original_list]
print(new_list) # [2, 4, 6, 8]Variable swapping
Swap two variables without a temporary variable:
a = 1
b = 2
a, b = b, a
print(a) # 2
print(b) # 1Split a string into a list
Use split() with default or custom separators:
string_1 = "My name is Chaitanya Baweja"
string_2 = "sample/ string 2"
print(string_1.split()) # ['My', 'name', 'is', 'Chaitanya', 'Baweja']
print(string_2.split('/')) # ['sample', ' string 2']Combine a list of strings into one string
Join list elements with a comma separator:
list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']
print(','.join(list_of_strings)) # My,name,is,Chaitanya,BawejaCheck if a string is a palindrome
Compare the string with its reverse:
my_string = "abcba"
if my_string == my_string[::-1]:
print("palindrome")
else:
print("not palindrome")
# Output: palindromeCount element frequencies in a list
Use collections.Counter:
from collections import Counter
my_list = ['a','a','b','b','b','c','d','d','d','d','d']
count = Counter(my_list)
print(count) # Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
print(count['b']) # 3
print(count.most_common(1)) # [('d', 5)]Check if two strings are anagrams
Compare character counts using Counter:
from collections import Counter
str_1, str_2, str_3 = "acbde", "abced", "abcda"
cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)
if cnt_1 == cnt_2:
print('1 and 2 anagram')
if cnt_1 == cnt_3:
print('1 and 3 anagram')
# Output: 1 and 2 anagramException handling with try‑except‑else‑finally
Demonstrate full exception block structure:
a, b = 1, 0
try:
print(a / b)
except ZeroDivisionError:
print("division by zero")
else:
print("no exceptions raised")
finally:
print("Run this always")
# Output:
# division by zero
# Run this alwaysEnumerate a list to get index/value pairs
Use enumerate():
my_list = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(my_list):
print('{0}: {1}'.format(index, value))
# 0: a
# 1: b
# 2: c
# 3: d
# 4: eCheck object memory usage
Use sys.getsizeof():
import sys
num = 21
print(sys.getsizeof(num)) # 28 in Python 3Merge dictionaries
Combine two dictionaries using unpacking:
dict_1 = {'apple': 9, 'banana': 6}
dict_2 = {'banana': 4, 'orange': 8}
combined_dict = {**dict_1, **dict_2}
print(combined_dict) # {'apple': 9, 'banana': 4, 'orange': 8}Measure execution time of a code block
Use time.time() to calculate elapsed microseconds:
import time
start_time = time.time()
for i in range(10**5):
a, b = 1, 2
c = a + b
end_time = time.time()
time_taken_in_micro = (end_time - start_time) * (10**6)
print(time_taken_in_micro)Additional useful snippets
Combine multiple strings into one:
list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']
print(' '.join(list_of_strings))Check if a string is a palindrome (alternative method):
my_string = "abcba"
print('palindrome' if my_string == my_string[::-1] else 'not palindrome')These snippets illustrate concise, Pythonic ways to handle common programming tasks, making your code cleaner and more efficient.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
