Fundamentals 9 min read

20 Essential Python Tricks to Boost Your Coding Efficiency

This article presents twenty practical Python snippets—including string reversal, title casing, unique element extraction, list repetition, comprehensions, variable swapping, splitting, joining, palindrome checking, Counter usage, anagram detection, exception handling, enumeration, memory sizing, dictionary merging, timing, flattening, random sampling, digit list conversion, and uniqueness verification—to help developers write cleaner, faster code.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
20 Essential Python Tricks to Boost Your Coding Efficiency

1. String reversal

str1 = "qwert"
rev_str1 = str1[::-1]
# output: trewq

2. Capitalize first letters

str1 = "this is a book"
print(str1.title())
# This Is A Book

3. Find unique characters in a string

str1 = "aabbccccdddd"
set1 = set(str1)
new_str = ''.join(set1)
print(new_str)

4. Repeat strings or lists

i = 4
str1 = "abcd"
list1 = [1, 2]
print(str1 * i)   # abcdabcdabcdabcd
print(list1 * i)   # [1, 2, 1, 2, 1, 2, 1, 2]

5. List comprehension

list1 = [1, 2, 3]
new_list1 = [2 * i for i in list1]
# [2, 4, 6]

6. Swap variables without a temporary

x = 1
y = 2
x, y = y, x
print(x)  # 2
print(y)  # 1

7. Split a string into a list of substrings

str1 = "This is a book"
str2 = "test/ str 2"
print(str1.split())          # ['This', 'is', 'a', 'book']
print(str2.split('/'))       # ['test', ' str 2']

8. Join a list of strings into a single string

list_str = ['This', 'is', 'a', 'book']
print(','.join(list_str))   # This,is,a,book

9. Check for palindrome strings

str1 = "qqaabb"
if str1 == str1[::-1]:
    print("回文")
else:
    print("不是")
# 不是

10. Count elements in a list using Counter

from collections import Counter
list1 = ['a', 'b', 'a', 'c', 'c', 'c']
count = Counter(list1)
print(count)
print(count['b'])
print(count.most_common(1))

11. Determine if two strings are anagrams

s1, s2, s3 = "acbde", "abced", "abcda"
c1, c2, c3 = Counter(s1), Counter(s2), Counter(s3)
if c1 == c2:
    print('1和2是异序词')
if c1 == c3:
    print('1和3是异序词')

12. Use try‑except‑else‑finally blocks

a, b = 1, 0
try:
    print(a / b)
except ZeroDivisionError:
    print("除数为0")
else:
    print("不存在异常")
finally:
    print("此段总是会执行")

13. Enumerate to get index/value pairs

list1 = ['a', 'b', 'c', 'd', 'e']
for idx, val in enumerate(list1):
    print('{0}:{1}'.format(idx, val))
# 0:a
# 1:b
# 2:c
# 3:d
# 4:e

14. Get memory size of an object

import sys
num = 21
print(sys.getsizeof(num))

15. Merge two dictionaries

dic1 = {'app': 9, 'banana': 6}
dic2 = {'banana': 4, 'orange': 8}
com_dict = {**dic1, **dic2}
# {'app': 9, 'banana': 4, 'orange': 8}

16. Measure code execution time

import time
s_time = time.time()
a, b = 1, 2
c = a + b
e_time = time.time()
time_taken_in_micro = (e_time - s_time) * (10**6)
print("程序运行的毫秒:{0} ms".format(time_taken_in_micro))

17. Flatten nested lists

from iteration_utilities import deepflatten
# shallow flatten
list1 = [[1, 2, 3], [3]]
print([item for sublist in list1 for item in sublist])
# deep flatten (unknown depth)
l = [[1,2,3],[4,[5]],[6,7]], [8,[9,[10]]]
print(list(deepflatten(l, depth=3)))

18. Random sampling from a list

import random
list1 = ['a', 'b', 'c', 'd', 'e']
ns = 2
samples = random.sample(list1, ns)
print(samples)  # e.g., ['a', 'c']

19. Convert an integer to a list of digits

nums = 123456
digit_list = list(map(int, str(nums)))
print(digit_list)  # [1,2,3,4,5,6]
# or using list comprehension
digit_list = [int(x) for x in str(nums)]
print(digit_list)

20. Check for uniqueness in a list

def unique(l):
    if len(l) == len(set(l)):
        print("所有元素是唯一的")
    else:
        print("存在重复")
unique([1,2,3,4])   # 所有元素是唯一的
unique([1,1,3,4])   # 存在重复
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonprogrammingcodeTipssnippets
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.