Comprehensions in Python

In the previous article we saw how we could obtain the even and odd elements of a list, separately and return them. Now we will explore the concept of Comprehensions in Python with regards to lists, sets and dictionaries. What is List Comprehension? List Comprehension provides us a shortcut to create a new list from another iterable data type(tuples, dictionaries etc), we can select certain items from it or all items from it. Let us understand through the use of examples:

``` l1= [x for x in range(11) if x%==0]
print(l1)
l2= [x for x in range(11) if x%!=0]
print(l2)
```
``````Output:
[0, 2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]``````

We have two list comprehensions here, the first one returns a list of even numbers from 0 to 10 and the second returns a list of odd numbers from 0 to 10. Alternatively the programs above could be written in this manner:

```l1=[ ]
for x in range(11):
if x%2==0:
l1.append(x)

l1=[ ]
for x in range(11):
if x%2!=0:
l1.append(x)
```

Programs involving use of Comprehensions in Python

We have discussed in earlier chapters, on how we could write functions to return smaller elements present in a list and how we can split even and odd elements from a list. Now we will see the simpler methods to achieve the same through the use of Comprehensions in Python.

```#Function to get a list that contains
#all those items of l that are smaller than x
def getSmaller(l, x):
return[e for e in l if e<x]
l= [5,15,12,3,7,11]
x=10
print(getSmaller(l,x))
```
``````Output:
[5, 3, 7]``````

Here, is a solution to the first problem, we write a function of two lines to handle the case. The comprehension statement simply checks while traversing through the list if the elements are smaller than x and then returns any that matches this condition.

```#Returns two lists, the frst list contains
#all even elements of l, and the second contains all odd elements
def getEvenOdd(l):
even=[x for x in l if x%2==0]
odd=[x for x in l if x%2!=0]
return even, odd

l= [10,3,20,5,12]
even, odd =getEvenOdd(l)
print(even)
print(odd)
```
``````Output:
[10, 20, 12]
[3, 5]``````

The program is able to traverse through the list and return the odd and even elements separately. Here are some more function examples of Comprehensions in Python, try to guess the output.

```s="geeksforgeeks"
l1=[x for x in s if x in "aeiou"]
print(l1)

l2=["geeks", "ide", "courses", gtg"]
l3=[x for x in l2 if x.startswith("g")]
print(l3)

l4=[x*2 for x in range(6)]
print(l4)
```
``````Output:
['e', 'e', 'o', 'e', 'e']
['geeks', 'gtg']
[0, 2, 4, 6, 8, 10]``````

Here is another example, look at the program below and try to guess the output:

```l1=["geeks", "for", "geeks", "gfg", "ide"]
l2=[x.upper() for x in l1 if x.startswith("g")]
```
``````Output:
["GEEKS," GEEKS", "GFG"``````

We have discussed many examples of list comprehensions so far, similar to lists we can also create sets using the comprehensions. This set can be created from any iterable such as range, list, another set, dictionary or tuple.

Here in the below example we are creating two sets using set comprehension from a list, so we have a list of items l=[10,20,3,4,10,20,7,3]

```l=[10,20,3,4,10,20,7,3]
s1={x for x in l if x%2==0}
s2={x for x in l if x%2!=0}
print(s1)
print(s2)
```
``````Output:
{10, 20, 4}
{3, 7}``````

The list contains some even values and some odd values, the comprehension is a set comprehension not a list comprehension as we utilize curly braces which signifies set data type in Python. The first set picks up all the even elements and the second picks up all the odd. Sets should contain distinct items so when we traverse and return the elements in the list though 10, 20 and 3 occur twice they are returned only once.

While creating a dictionary it is necessary to maintain key-value pairs.

```l1=[1,3,4,2,5]
d1={x: x ** 3 for x in l1}
print(d1)

d2={x:f"ID{x}" for x in range(5)}
print(d2)

l2=[101,103,102]
l3=["gfg", "ide", "courses"]
d3={l2[i]:l3[i] for i in range(len(l2))}
print(d3)
```

In these three examples, in the first segment we are creating a dictionary. The key of this dictionary is every element of the list and value of this dictionary is element cube. In the second example, we are generating dictionary through the use of range ..the key of this dictionary is 0, 1, 2 ,3 , 4.We are using f-strings to create value, so values are going to be id 0, id 1, id 2, id 3 and id 4.

In the third example we have two lists l1 and l2. We are utilizing the elements of l2 as keys and l3 as values, they must both match the same length.

``````Output:
{1: 1, 3: 27, 4: 64, 2: 8, 5: 125}
{0: 'ID0', 1: 'ID1', 2: 'ID2', 3: 'ID3', 4: 'ID4'}
{101: 'gfg', 103: 'ide', 102: 'courses'}``````

However, there is a better way to create dictionary from two different lists through the use of the zip( ) function. zip( ) is a built-in function that takes in multiple iterables and it creates mapping of these items in the iterables. It will create a collection of mappings in the form of a tuple

```d3=dict(zip(l2,l3))
```

Here is our last example, of dictionary comprehensions. We are reversing or inverting mappings of the dictionary, let’s see the logic behind it’s implementation:

```#Inverting a Dictionary(Key becomes value)
#and value becomes key)
d1={101:"gfg", 103 : "practice", 102: "ide"}
d2={v:k for (k,v) in d1.items()}
print(d2)
```
``````Output:
{'gfg': 101, 'practice': 103, 'ide': 102}``````

For every key item in d1, we create key value pair in d2 where key is value and value is key .

Thus we have seen the utility of the Comprehensions in Python. In the next article, we will look at how we can determine the average or mean of a list in python.

: