Python One‑Liner Tricks: Summation, List Deduplication, Comprehensions, Swapping, Sorting, Counting, Space Removal, Regex, Doubling, and Multiplication Table
This article presents a collection of concise Python one‑liner techniques covering integer summation, list deduplication, list comprehensions, value swapping, length‑based sorting, character counting, whitespace removal, Chinese character regex, element doubling, and generating a multiplication table, each illustrated with brief explanations and code snippets.
Using a single line of code, you can sum integers from 1 to 100 with sum(range(1,101)) , remembering that range(1,101) excludes the upper bound.
To remove duplicates from a list, convert it to a set and back to a list in one line: list(set(my_list)) .
List comprehensions allow you to construct new lists succinctly, e.g., [expr for x in lst] or with a condition [expr for x in lst if cond] , enabling element transformation and filtering in a single expression.
Swap two values without a temporary variable using tuple unpacking: a, b = b, a .
Sort a list by the length of its string elements with my_list.sort(key=len) , which modifies the list in place.
Count occurrences of a specific character in a string using my_string.count('a') , which is case‑sensitive.
Remove spaces from a string either by my_string.replace(' ', '') or by splitting and joining: ''.join(my_string.split(' ')) .
Match Chinese characters using a regular expression pattern [\u4e00-\u9fa5]+ .
Double each element in a list with a one‑liner using list(map(lambda x: x*2, my_list)) .
Generate a formatted multiplication table in a single line: print('\n'.join(' '.join('%s*%s=%-2s'%(y,x,x*y) for y in range(1,x+1)) for x in range(1,10))) .
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.