Fundamentals 10 min read

20 Essential Python Tips to Boost Your Programming Efficiency

This article presents twenty practical Python tricks—including string reversal, title casing, unique element extraction, list multiplication, list comprehensions, variable swapping, splitting and joining strings, palindrome checking, Counter usage, anagram detection, exception handling, enumeration, memory size inspection, dictionary merging, timing code execution, flattening nested lists, random sampling, digit list conversion, and uniqueness testing—to help developers write cleaner, faster, and more readable code.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
20 Essential Python Tips to Boost Your Programming Efficiency

1. String Reversal Use slicing to reverse a string.

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

2. Capitalize First Letter Convert a string to title case with the title() method.

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

3. Find Unique Elements in a String Create a set from the string and join its elements.

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

4. Repeat a String or List Use the * operator to duplicate a string or list multiple times.

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 Build a new list by applying an expression to each element of an existing list.

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

6. Swap Variables Without a Temporary Variable Use tuple unpacking.

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

7. Split a String into a List of Sub‑strings Use the split() method with an optional delimiter.

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 Use join() with a separator.

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

9. Check for Palindrome Strings Compare a string with its reversed version.

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

10. Count Elements in a List Use collections.Counter to obtain frequencies and the most common element.

from collections import Counter
list1 = ['a', 'b', 'a', 'c', 'c', 'c']
count = Counter(list1)
print(count)                # Counter({'c': 3, 'a': 2, 'b': 1})
print(count['b'])          # 1
print(count.most_common(1))# [('c', 3)]

11. Determine Whether Two Strings Are Anagrams Compare their Counter objects.

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 a try‑except‑else Block Execute code that may raise an exception and run the else clause when no exception occurs.

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

13. Enumerate to Get Index‑Value Pairs Iterate over a list with both index and value.

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 Usage of an Object Use sys.getsizeof().

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

15. Merge Two Dictionaries In Python 3, use the unpacking operator **.

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

16. Measure Code Execution Time Use time.time() and calculate the difference in microseconds.

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 Use iteration_utilities.deepflatten for unknown depth or a simple list comprehension for one‑level nesting.

from iteration_utilities import deepflatten
l = [[1,2,3],[4,[5]],[6,7]]
print(list(deepflatten(l, depth=3)))
# [1,2,3,4,5,6,7]

18. Random Sampling from a List Use random.sample() or secrets.SystemRandom() for cryptographically secure samples.

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

import secrets
s_rand = secrets.SystemRandom()
samples = s_rand.sample(list1, ns)
print(samples)  # e.g., ['c', 'd']

19. Convert an Integer to a List of Digits Use map(int, str(num)) or a list comprehension.

nums = 123456
digit_list = list(map(int, str(nums)))
print(digit_list)  # [1,2,3,4,5,6]

digit_list = [int(x) for x in str(nums)]
print(digit_list)  # [1,2,3,4,5,6]

20. Check Uniqueness of Elements in a List Compare the length of the list with the length of its set.

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.

data manipulationTipscode-snippets
Python Programming Learning Circle
Written by

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.

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.