Fundamentals 10 min read

10 Useful Python Tips and Tricks for Beginners

This article presents ten practical Python tips and tricks, covering list comprehensions, efficient list traversal, element swapping, list initialization, string construction, tuple returns, dictionary access, library usage, slicing and stepping, and indentation best practices, each illustrated with clear code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
10 Useful Python Tips and Tricks for Beginners

Below are ten useful Python tips and tricks. Some address common beginner mistakes and show more Pythonic ways to write code.

1. List Comprehension

Given a list bag = [1, 2, 3, 4, 5] , you may want to double every element to obtain [2, 4, 6, 8, 10] . A verbose approach is:

bag = [1, 2, 3, 4, 5]
for i in range(len(bag)):
    bag[i] = bag[i] * 2

A more concise way uses a list comprehension:

bag = [elem * 2 for elem in bag]

This is called a Python list comprehension.

2. Traversing a List

Instead of iterating by index:

bag = [1, 2, 3, 4, 5]
for i in range(len(bag)):
    print(bag[i])

Iterate directly over the elements:

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

Traditional swapping (like in Java or C) uses a temporary variable:

a = 5
b = 10
tmp = a
a = b
b = tmp

Python allows a more natural swap:

a, b = b, a

4. Initializing a List

A naïve way to create a list of ten zeros:

bag = []
for _ in range(10):
    bag.append(0)

A cleaner method uses multiplication:

bag = [0] * 10

Be aware that multiplying a list of mutable objects creates shallow copies:

bag_of_bags = [[0]] * 5  # all sub‑lists refer to the same object
bag_of_bags[0][0] = 1      # changes every sub‑list

Use a comprehension to create independent sub‑lists:

bag_of_bags = [[0] for _ in range(5)]

5. Constructing Strings

Concatenating many parts can become unreadable:

name = "Raymond"
age = 22
born_in = "Oakland, CA"
string = "Hello my name is " + name + " and I'm " + str(age) + " years old. I was born in " + born_in + "."
print(string)

Use .format() for a cleaner solution:

string = "Hello my name is {0} and I'm {1} years old. I was born in {2}.".format(name, age, born_in)
print(string)

6. Returning Tuples

A function can return multiple values as a tuple:

def binary():
    return 0, 1
zero, one = binary()

If you only need one value, you can ignore the other with an underscore:

zero, _ = binary()

7. Accessing Dictionaries

When counting occurrences, a common pattern is:

countr = {}
for i in bag:
    if i in countr:
        countr[i] += 1
    else:
        countr[i] = 1

A safer and shorter way uses dict.get :

countr = {}
for i in bag:
    countr[i] = countr.get(i, 0) + 1

You can also build the dictionary with a comprehension:

countr = {num: bag.count(num) for num in bag}

8. Using Libraries

Instead of writing your own counting loop, import Counter from the standard library:

from collections import Counter
countr = Counter(bag)
for i in range(10):
    print("Count of {}: {}".format(i, countr[i]))

Libraries provide tested, often optimal implementations and let you focus on higher‑level logic.

9. Slicing and Stepping

Extract the first five elements:

for elem in bag[:5]:
    print(elem)

Extract the last five elements:

for elem in bag[-5:]:
    print(elem)

Step through a list, taking every second element:

for elem in bag[::2]:
    print(elem)
# or create the stepped list directly
bag = list(range(0, 10, 2))
print(bag)

Reverse a list with list[::-1] .

10. Tabs vs. Spaces

Mixing tabs and spaces leads to IndentationError: unexpected indent . Choose one style and stick to it throughout a project. Most Python codebases use four spaces per indentation level.

For more details, see the original article and the recommended reading list.

Pythonbest practicesdictionarylist comprehensiontipsString Formatting
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

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