List and Dictionary Comprehension in Python💡

We often need loops to create lists and dictionaries with some logic.

List and Dictionary Comprehension are a more elegant and Pythonic way to do the same process.:rocket:

It makes you write the same For Loop logic in just one line, making life easier for you.

Let’s look at the code in the image.

If you have multiple variables, you can write nested loops within the same comprehension as well.

Multiple logic can also be included for filtering the elements that are to be added.:zap:

With dictionary comprehension, a similar process is followed, except that it takes key, value pairs instead of single variables.

You can also invert the dictionary by making keys as values and values as keys.

More nesting, logic and even lambda expressions can be included in these comprehensions.:rocket:

However, you should not go too far exploiting these expressions by putting a lot of logic in one line.

The more you complicate it, the more you defeat its purpose.

These examples are just a tip of the ice. What examples do you know of ?:question:

#python #datascience #machinelearning