Python comprehensions In a nutshell

Introduction

If you’re a Python programmer, then you know how powerful and flexible the list comprehension syntax is. It allows us to create lists, dictionaries and sets in one line of code. Here’s an example:

>>> [x**2 for x in list]

This raises every element of the list to the power of 2

List Comprehensions

List comprehensions are a way to create lists. They’re written as

[ expression for item in iterable ]

and the expression is evaluated for each item in the iterable, which can be any iterable object such as a list or array.

The result of this type of comprehension is a lsit containing all the items that match your criteria, so it’s useful for building up larger lists from smaller ones.

Dictionary Comprehensions

You can create a dictionary of values in one line of code using a dictionary comprehension. A dictionary comprehension is a way to create dictionaries that are more useful than the normal dict() function, which returns only one key-value pair at a time.

Python Comprehensions are a useful tool for creating lists, dictionaries, and sets in one line of code.

Python has a lot of functions that can be used to create lists and sets, but they’re not all as intuitive to use as the list or set built-in functions. For example, when you want to make a list of all numbers between 1 and 100 you’ll have to write this line:

>>> [x for x in range(1, 101)]

This will get you back your list with all the numbers in it. Now if we wanted another list with those numbers but only ones divisible by 3, we need something more like this:

>>> [x for x in range(1, 101) if x % 3 == 0]

Conclusion

Python comprehensions are a useful and powerful tool for generating lists, dictionaries, and sets in one line of code. They are especially useful when you want to create large lists with complex filtering conditions.

Thanks for reading, follow for more


Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies and get more readers

Join other developers and claim your FAUN account now!

Avatar

Sotirios Kapartzianis

@sotiris
A Computer guy with experience on gaming, cooking, money and banging his head on the wall when frustrated
Stats
15

Influence

351

Total Hits

2

Posts