10 Smooth Python Tricks for Python Gods
This article presents ten practical Python tricks—including string reversal, variable unpacking, itertools usage, slicing, grouping adjacent items, generator next(), Counter, and deque operations—demonstrating how to leverage built‑in functions and standard‑library modules to write cleaner, more efficient code.
Although Python appears to be a simple language that anyone can learn, mastering it is surprisingly challenging for many people.
Python is indeed easy to learn, but becoming proficient can be difficult.
In Python there are many ways to solve a problem, yet it is easy to make mistakes or reinvent parts of the standard library, wasting time simply because you are unaware of existing modules.
Unfortunately, the Python standard library is a massive beast, and its ecosystem is even larger; with millions of modules available, you can learn useful techniques related to scientific computing by exploring the standard library and popular packages.
Reverse String
Although it seems basic, manually looping over characters to reverse a string can be tedious; fortunately Python provides a simple built‑in operation using slicing a[::-1] .
<code>a = "!dlrow olleH"</code>
<code>backward = a[::-1]</code>Assigning to Variables
In many languages you must iterate over an array or access elements by position to assign them to separate variables; Python offers a cooler way by unpacking the entire list directly into variables of matching length.
<code>firstdim = array[1]</code> <code>array = [5, 10, 15, 20]</code>
<code>five, ten, fift, twent = array</code>itertools
If you plan to spend any time with Python, you’ll want to become familiar with itertools , a standard‑library module that simplifies complex iteration, makes code faster and more concise.
<code>c = [[1, 2], [3, 4], [5, 6]]</code>
<code># Convert this matrix to a 1‑dimensional list</code>
<code>import itertools as it</code>
<code>itnewlist = list(it.chain.from_iterable(c))</code>Smart Unpacking
Iteratively unpacking values can be time‑consuming; Python allows the use of * to collect the remaining items into a new list.
<code>a, *b, c = [1, 2, 3, 4, 5]</code>Enumerate
If you are unfamiliar with enumerate , it provides the index of each value in a list, which is especially useful in data‑science contexts when working with arrays.
<code>for i, w in enumerate(array):</code>
<code> print(i, w)</code>Name Slicing
Splitting lists in Python is easy, and naming slices can be valuable, particularly for linear‑algebra operations.
<code>a = [0, 1, 2, 3, 4, 5]</code>
<code>LASTTHREE = slice(-3, None)</code>
<code>print(a[LASTTHREE])</code>Group Adjacent Lists
You can group adjacent elements in a list using zip , but a more concise approach employs a lambda expression.
<code>a = [1, 2, 3, 4, 5, 6]</code>
<code>group_adjacent = lambda a, k: zip(*([iter(a)] * k))</code>
<code>group_adjacent(a, 3) # [(1, 2, 3), (4, 5, 6)]</code>
<code>group_adjacent(a, 2) # [(1, 2), (3, 4), (5, 6)]</code>Generator next() Iteration
Instead of manually managing an index counter, you can use next() to retrieve the next value from a generator, which maintains its own internal state.
<code>g = (x ** 2 for x in range(10))</code>
<code>print(next(g))</code>
<code>print(next(g))</code>Counter
The collections.Counter class provides an easy way to count occurrences in a list, useful for obtaining total counts, identifying empty counts, and finding unique values.
<code>import collections</code>
<code>A = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7])</code>
<code>A # Counter({3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1, 7: 1})</code>
<code>A.most_common(1) # [(3, 4)]</code>
<code>A.most_common(3) # [(3, 4), (1, 2), (2, 2)]</code>Deque
The collections.deque type offers efficient double‑ended queue operations; you can append, prepend, extend, rotate, and pop elements with simple method calls.
<code>import collections</code>
<code>Q = collections.deque()</code>
<code>Q.append(1)</code>
<code>Q.appendleft(2)</code>
<code>Q.extend([3, 4])</code>
<code>Q.extendleft([5, 6])</code>
<code>Q.pop()</code>
<code>Q.popleft()</code>
<code>Q.rotate(3)</code>
<code>Q.rotate(-3)</code>
<code>print(Q)</code>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.