DEV Community

Ilya R
Ilya R

Posted on

Python3 Abbreviations

Python3 is a very flexible language. It has a lot of different features that make it easier to work with lists and dictionaries. Today I propose to consider a couple of techniques on how to reduce the amount of code when working with lists and dictionaries

It often happens that we need to iterate through a list and, at the same time, changing and processing each element, get a new list with processed elements.

Let's assume we have a list of integers. And we need to go through it and square each element.

nums = [1, 2, 3]

The simplest way to do this is:

for num in nums:
    squares.`append`(num**2)
Enter fullscreen mode Exit fullscreen mode

But we can reduce this code to one line:
squares= [ num ** 2 for num in nums]

In such abbreviations we can use conditional statements.

For example, let's take a list of cars. We are interested in all cars starting with the letter M.
cars = [”Toyota”, “Mitsubishi”, “Honda”, “Mazda”]

We could also write a loop as in the previous example and in the body of the loop check through ‘if’ statment the capital letter in the name of the car. But we can fit everything into one line.
starts = [car for car in cars if car.startsWith(”M”)]

Let's see how we can work with a dictionary using the same method.

Let's assume we have a dictionary of integers.
nums = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

And here we also need to square each number. Again, we could write a loop and do certain things inside the body of the loop, but we can fit everything into one line.
squares= {k:v**2 for (k,v) in nums.items()}

Thus, we can significantly reduce the amount of code and make it more readable. And the less code we have, the less likely it is that we will make a mistake somewhere.

Top comments (0)