# List comprehension in python

## List comprehension in python

Comprehension of any of the data structures is an elegant way of completing the requirement with less coding effort though initially, it may look a bit complex to beginners.

We can create lists, sets, and dictionaries just like mathematical statements in one line only. The syntax of comprehension is easier to grasp.

A list comprehension generally consists of these parts :

1. Output expression,
2. Input sequence,
3. A variable representing a member of the input sequence and
4. An optional predicate part.

## Syntax:

lst = [<Output expression> for <variable (member of input sequence) > in <input sequence> <optional predicate part>]

lst = [x ** 2 for x in range (1, 11) if x % 2 == 1]

here,

• x ** 2 is output expression,
• range (1, 11) is input sequence,
• x is variable i.e. member of input sequence
• if x % 2 == 1 is predicate part.

let’s try a small task with or without comprehension, suppose we need a list of all the numbers between 1 to 10 which are multiple of 3, traditionally we would do it as below Now by using list comprehension the same task can be done in one line as below Comprehensions are not only limited to lists, but we may also use them with sets and dictionaries as well, now let’s try comprehension with a dictionary.

suppose I have a dictionary as below which needs to be extended up to 1000 key-value pairs It will definitely be a tedious task if we do it manually but thanks to comprehension we can do it in a very small code, here I have used F-String  else we may also use + operator to concatenate. we can also reverse the key and values of a dictionary with the help of dictionary comprehension, here is how we would do it. Similar to list comprehension we can create set comprehension however as it’s a set so it will only have unique values. Now it will also be good if we practice a few exercises on comprehensions, in my next blog I will be adding a few exercises so that you can check your logic and fill all the gaps.

This site uses Akismet to reduce spam. Learn how your comment data is processed.