🔥 Burn Fat Fast. Discover How! 💪

5 examples on how to improve your Python code Полезные пример | Python/ django

5 examples on how to improve your Python code

Полезные примеры того, как улучшить ваш код на Python

1. Using List Comprehensions

squares = []

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

print(squares)

2. Using Generators

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

3. Using the zip() function

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

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

4. Using DefaultDict

from collections import defaultdict

s = 'hello world'

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

print(d)

5. Using enumerate()

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

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

Techniques to Write Better Python Code
Улучшение Python-кода

@pythonl