Python Tips: Variable Swapping, Comprehensions, Counter, JSON Pretty‑Print, FizzBuzz, and More
This article presents a collection of practical Python techniques, including variable swapping without a temporary variable, using dictionary and set comprehensions, leveraging the Counter class for counting, pretty‑printing JSON, solving FizzBuzz concisely, inline conditional expressions, list slicing, dictionary get method, and generating combinations with itertools.
This guide gathers a series of useful Python tricks that illustrate concise syntax and built‑in library features.
Variable swapping can be done in a single line without a temporary variable:
>> a = 3
>>> b = 6
>>> a, b = b, a
>>> print(a) # 6
>>> print(b) # 3Dictionary and set comprehensions provide compact ways to build new collections:
some_list = [1, 2, 3, 4, 5, 2, 5, 1, 4, 8]
even_set = {x for x in some_list if x % 2 == 0}
d = {x: x % 2 == 0 for x in range(1, 11)}The collections.Counter class simplifies counting occurrences:
from collections import Counter
c = Counter('hello world')
print(c.most_common(2)) # [('l', 3), ('o', 2)]Pretty‑printing JSON improves readability, especially for large structures:
import json
print(json.dumps(data))
print(json.dumps(data, indent=2))A compact FizzBuzz solution can be written using slicing:
for x in range(1, 101):
print('fizz'[x%3*len('fizz'):] + 'buzz'[x%5*len('buzz'):] or x)Inline conditional expressions allow one‑line decisions:
print('Hello' if True else 'World')List concatenation and slicing examples demonstrate quick data manipulation:
nfc = ['Packers', '49ers']
af c = ['Ravens', 'Patriots']
print(nfc + afc) # ['Packers', '49ers', 'Ravens', 'Patriots']
print(x[:3]) # first three items
print(x[1:5]) # middle four items
print(x[::2]) # odd‑indexed itemsUsing dict.get avoids explicit try/except when a key may be missing:
is_admin = data.get('admin', False)The itertools module can generate combinations efficiently:
from itertools import combinations
for game in combinations(teams, 2):
print(game)Because True and False are just names, they can be reassigned (though not recommended):
False = True
if False:
print('Hello')
else:
print('World') # prints HelloPython 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.