12 Quick Python Tricks to Boost Your Coding Efficiency
This article presents twelve practical Python techniques—including variable swapping, dictionary and set comprehensions, Counter usage, inline conditionals, chained comparisons, zip iteration, enumerate, list initialization, joining, safe dict access, slicing, and itertools combinations—each illustrated with clear code examples and expected outputs to help programmers write cleaner and more efficient code.
Programming cannot be mastered instantly; the following twelve Python tricks can make learning and coding more efficient.
01 Swap variables
Python swaps values without a temporary variable:
a = 3 b = 6 a, b = b, a print(a) print(b)Output:
6 302 Dictionary and set comprehensions
List comprehensions create lists concisely; the same syntax works for sets and dictionaries since Python 3.1.
some_list = [1, 2, 3, 4, 5] another_list = [x + 1 for x in some_list] print(another_list)Output:
[2, 3, 4, 5, 6]Set comprehension example:
some_list = [1, 2, 3, 4, 5, 2, 5, 1, 4, 8] even_set = {x for x in some_list if x % 2 == 0} print(even_set)Output (order may vary):
{8, 2, 4}Dictionary comprehension example:
d = {x: x % 2 == 0 for x in range(1, 11)} print(d)Output:
{1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}03 Counting with Counter
The collections.Counter class quickly counts element frequencies:
from collections import Counter c = Counter('Hello World, Hello Forchange') print(c) print(c.most_common(3))Output:
Counter({'l': 5, 'o': 4, 'e': 3, ' ': 3, 'H': 2, 'r': 2, 'W': 1, 'd': 1, ',': 1, 'F': 1, 'c': 1, 'h': 1, 'a': 1, 'n': 1, 'g': 1}) [('l', 5), ('o', 4), ('e', 3)]04 Inline if statement
Python can evaluate an expression conditionally in a single line:
print('Hello') if True else ('World')Output:
Hello05 Chained comparisons
Multiple comparisons can be written compactly:
x = 2 if 3 > x > 1:
print(x) if 1 < x > 0:
print(x)Output:
2 206 Iterate two lists simultaneously
Use zip to loop over two sequences in parallel:
west = ["Lakers", "Warriors"] east = ["Bulls", "Celtics"] for teama, teamb in zip(west, east):
print(teama + " vs. " + teamb)Output:
Lakers vs. Bulls Warriors vs. Celtics07 Enumerate with index
Retrieve both index and value while iterating:
teams = ["Lakers", "Warriors", "Bulls", "Celtics"] for index, team in enumerate(teams):
print(index, team)Output:
0 Lakers 1 Warriors 2 Bulls 3 Celtics08 Initialize list with repeated values
items = [0] * 3 print(items)Output:
[0, 0, 0]09 Convert list to string
teams = ["Lakers", "Warriors", "Bulls", "Celtics"] print(','.join(teams))Output:
Lakers,Warriors,Bulls,Celtics10 Safe dictionary lookup with get
data = {'user': 1, 'name': 'Max', 'three': 4} is_admin = data.get('admin', False)Result: is_admin is False without raising KeyError .
11 List slicing for subsets
Retrieve parts of a list using slice notation:
x = [1,2,3,4,5,6] print(x[:3]) # first three print(x[1:5]) # middle four print(x[3:]) # last three print(x[::2]) # odd-indexed items print(x[1::2]) # even-indexed itemsOutputs respectively:
[1, 2, 3] [2, 3, 4, 5] [4, 5, 6] [1, 3, 5] [2, 4, 6]12 Iteration tools with itertools.combinations
Generate all 2‑element combinations of a list efficiently:
from itertools import combinations teams = ["Lakers", "Warriors", "Bulls", "Celtics"] for combo in combinations(teams, 2):
print(combo)Output:
('Lakers', 'Warriors') ('Lakers', 'Bulls') ('Lakers', 'Celtics') ('Warriors', 'Bulls') ('Warriors', 'Celtics') ('Bulls', 'Celtics')These concise patterns illustrate how Python’s expressive syntax and standard‑library utilities can dramatically simplify common programming tasks.
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.