Some Python tricks for you

5 examples on how to improve your Python code

Simone Rigoni
3 min readJun 1, 2023
Photo by Timothy Dykes on Unsplash

Catchy title apart here some little suggestions that can help you write more efficient and readable Python code:

1. Using List Comprehensions

List comprehensions are a concise way to create lists in Python. Instead of using a for loop to create a list, you can use a single line of code. For example, instead of writing:

squares = []

for x in range(10):
squares.append(x**2)

print(squares)

You can use a list comprehension like this:

squares = [x**2 for x in range(10)]

print(squares)
List comprehensions examples execution

2. Using Generators

Generators are a type of iterator that allow you to iterate over a sequence of values without creating the entire sequence in memory at once. This can be useful when working with large datasets. Here is an example of using a generator to iterate over a file:

with open('example.txt') as f:
for line in (line.strip() for line in f):
print(line)
example.txt
Generators example execution

3. Using the zip() function

The zip() function in Python allows you to combine two or more lists into a single list of tuples. For example, you can use zip() to combine two lists of names and ages:

names = ['Pippo', 'Pluto', 'Paperino']
ages = [25, 30, 35]

for name, age in zip(names, ages):
print(f'{name} is {age} years old')
zip() function example execution

4. Using DefaultDict

The defaultdict class in the collections module is a useful tool for working with dictionaries. It allows you to define a default value for a key that does not exist in the dictionary. For example, you can use defaultdict to count the occurrences of each letter in a string:

from collections import defaultdict

s = 'hello world'

d = defaultdict(int)
for c in s:
d[c] += 1

print(d)
DefaultDict example execution

5. Using enumerate()

The enumerate() function in Python allows you to iterate over a sequence and keep track of the index of each element. This can be useful when you need to access both the index and the value of each element in a sequence. Here is an example of using enumerate() to print the index and value of each item in a list:

fruits = ['apple', 'banana', 'cherry']

for i, fruit in enumerate(fruits):
print(f'{i}: {fruit}')
enumerate() example execution

These are just a few examples that can help you write more concise, readable and efficient code.

Outro

I hope the story was interesting and thank you for taking the time to read it. On my Blogspot you can find the same post in Italian. Let me know if you have any question and if you like the content that I create feel free to buy me a coffee.

--

--

Simone Rigoni
Simone Rigoni

No responses yet