Member-only story
Use These 5 Techniques to Write Concise Python Code
Make your Python code more readable
Python is a beginner-friendly language that many people start their learning to code with it. Once you have Python installed on your computer, it just takes one line of code to finish your “Hello World” program. After a while that you use Python, you’ll be fascinated by how flexible Python is to provide multiple approaches to the same jobs. However, some solutions are more concise than others, which many refer to as Pythonic approaches.
In this article, I want to share 5 techniques that you can apply to your daily projects. Without further ado, let’s get it started.
1. Comprehensions and Generator Expressions
When you start with an iterable, such as a list, you can use comprehensions to create lists, dictionaries, and sets. Suppose that you have a list of numbers to start with:
numbers = [-2, -1, 1, 2]
You can create a list of squares from this list by using list comprehension, which has the syntax: [expression for x in iterable]
.
squares_list = [x*x for x in numbers]
assert squares_list == [4, 1, 1, 4]
If you want to create a dictionary, you can use dictionary comprehension, which has the…