What it is
The so called “Pythonic” way of coding is a practice that focuses on leveraging Python’s built-in features that makes the code more concise.
Is an elegant and efficient way of writing Python by leaning on the language’s idioms, which leads to a more readable and maintainable codebase.
Example
This is a non-Pythonic way of filtering a list of numbers to only include the even ones, and then squaring them:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = []
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
result.append(numbers[i] ** 2)
print(result)This other snippet does the same thing, but in a more Pythonic way using a list comprehension:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = [n ** 2 for n in numbers if n % 2 == 0]
print(result)This is an improvement because now the code is more legible.