10 Essential Python Tricks Every Beginner Should Know
This guide presents ten practical Python techniques—from list comprehensions and efficient looping to elegant swapping, list initialization, string formatting, multiple returns, dictionary access, using Counter, slicing, and consistent indentation—helping new programmers write cleaner, more Pythonic code.
1. List Comprehension
Given a list bag = [1, 2, 3, 4, 5], you can double each element concisely with a list comprehension:
bag = [elem * 2 for elem in bag]2. Traversing a List
Avoid indexing loops like:
for i in range(len(bag)):
print(bag[i])Instead iterate directly:
for i in bag:
print(i)If you need both index and element, use enumerate:
for index, element in enumerate(bag):
print(index, element)3. Swapping Elements
Instead of using a temporary variable, swap values in one line:
a, b = b, a4. Initializing a List
To create a list of ten zeros, use the multiplication shortcut: bag = [0] * 10 Be aware of shallow copies when the list contains mutable objects. For independent sub‑lists, use a comprehension:
bag_of_bags = [[0] for _ in range(5)]5. Constructing Strings
Instead of concatenating many parts, use str.format for readability:
string = "Hello my name is {0} and I'm {1} years old. I was born in {2}.".format(name, age, born_in)6. Returning Multiple Values
Return a tuple and unpack it directly:
def binary():
return 0, 1
zero, one = binary()If you only need the first value, use an underscore for the unused part:
zero, _ = binary()7. Accessing Dictionaries
Use dict.get to provide a default value and avoid KeyError: countr[i] = countr.get(i, 0) + 1 Alternatively, a dictionary comprehension can build the count map:
countr = {num: bag.count(num) for num in bag}8. Using Libraries
The collections.Counter class efficiently counts occurrences:
from collections import Counter
countr = Counter(bag)9. Slicing and Stepping
Extract sub‑lists with list[start:stop:step]:
for elem in bag[:5]:
print(elem)Step through a list with a stride:
for elem in bag[::2]:
print(elem)Reverse a list with list[::-1].
10. Tabs vs. Spaces
Consistently use either tabs or spaces for indentation; most Python style guides recommend four spaces to avoid IndentationError.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
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.
