Fundamentals 10 min read

30 Python Tips and Tricks to Supercharge Your Coding

Discover a curated collection of practical Python tips—from swapping variables without a temporary placeholder and mastering list, set, and dictionary comprehensions to leveraging Counter for counting, pretty‑printing JSON, solving FizzBuzz, using inline if statements, and more—to enhance your coding efficiency and readability.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
30 Python Tips and Tricks to Supercharge Your Coding

Python meets the expectations of many programmers looking for an efficient, high‑level language, offering concise syntax that can replace verbose C/C++ code.

01 Variable Swapping

In Python you can swap two variables without a temporary placeholder:

>a=3
>b=6
>a,b=b,a
>print(a)  # 6
>print(b)  # 3

02 Dictionary and Set Comprehensions

Python supports list, set, and dictionary comprehensions for concise data construction.

# List comprehension
some_list = [1, 2, 3, 4, 5]
another_list = [x + 1 for x in some_list]
# Set comprehension (Python 3.1+)
some_list = [1,2,3,4,5,2,5,1,4,8]
even_set = {x for x in some_list if x % 2 == 0}
# Dictionary comprehension
d = {x: x % 2 == 0 for x in range(1, 11)}

03 Counter for Counting

The collections.Counter class provides an easy way to count hashable objects.

from collections import Counter
c = Counter('hello world')
print(c)               # Counter({'l': 3, 'o': 2, ...})
print(c.most_common(2)) # [('l', 3), ('o', 2)]

04 Pretty‑Printing JSON

Use the json module with the indent parameter or pprint for readable output.

import json
print(json.dumps(data))
print(json.dumps(data, indent=2))

05 Solving FizzBuzz

A compact solution prints numbers 1‑100, replacing multiples of 3 with "fizz", multiples of 5 with "buzz", and both with "fizzbuzz".

for x in range(1, 101):
    print("fizz")[x%3*len('fizz')::] + "buzz"[x%5*len('buzz')::] or x

06 Inline If Statement

print("Hello") if True else print("World")
# Output: Hello

07 Concatenating Lists

nfc = ["Packers", "49ers"]
af c = ["Ravens", "Patriots"]
print(nfc + afc)  # ['Packers', '49ers', 'Ravens', 'Patriots']
print(str(1) + " world")  # 1 world

08 Numeric Comparisons

x = 2
if 3 > x > 1:
    print(x)  # 2
if 1 < x > 0:
    print(x)  # 2

09 Iterating Two Lists Simultaneously

nfc = ["Packers", "49ers"]
af c = ["Ravens", "Patriots"]
for teama, teamb in zip(nfc, afc):
    print(teama + " vs. " + teamb)
# Packers vs. Ravens
# 49ers vs. Patriots

10 Enumerating with Index

teams = ["Packers", "49ers", "Ravens", "Patriots"]
for index, team in enumerate(teams):
    print(index, team)
# 0 Packers
# 1 49ers
# 2 Ravens
# 3 Patriots

11 List Comprehension for Even Numbers

numbers = [1,2,3,4,5,6]
even = [n for n in numbers if n % 2 == 0]

12 Dictionary Comprehension

teams = ["Packers", "49ers", "Ravens", "Patriots"]
print({key: value for value, key in enumerate(teams)})
# {'49ers': 1, 'Ravens': 2, 'Patriots': 3, 'Packers': 0}

13 Initializing List Values

items = [0] * 3
print(items)  # [0, 0, 0]

14 Converting List to String

teams = ["Packers", "49ers", "Ravens", "Patriots"]
print(", ".join(teams))
# Packers, 49ers, Ravens, Patriots

15 Getting Elements from a Dictionary

Use dict.get to provide a default value instead of a try/except block.

data = {"user": 1, "name": "Max", "three": 4}
is_admin = data.get("admin", False)

16 Subsetting Lists

x = [1,2,3,4,5,6]
print(x[:3])   # [1,2,3]
print(x[1:5])  # [2,3,4,5]
print(x[3:])   # [4,5,6]
print(x[::2])  # [1,3,5]
print(x[1::2]) # [2,4,6]

17 itertools Combinations

from itertools import combinations
teams = ["Packers", "49ers", "Ravens", "Patriots"]
for game in combinations(teams, 2):
    print(game)
# ('Packers', '49ers')
# ('Packers', 'Ravens')
# ...

18 False == True

Demonstrates that False and True are assignable global names, though doing so is discouraged.

False = True
if False:
    print("Hello")
else:
    print("World")
# Output: Hello

Article originally published by Python Programming Learning Circle (© original author).

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.

PythonprogrammingComprehensionsTips
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.