Computer >> Computer tutorials >  >> Programming >> Python

Example Comprehensions in Python


With comprehensions you can construct python sequences. In this article we will see how to create and access such sequences.

Below are the different types of comprehensions in python.

  • List Comprehensions
  • Dictionary Comprehensions
  • Set Comprehensions
  • Generator Comprehensions

List comprehension

There are various ways we can create a list and access the elements in it.

Using for loop

Example

# Cretae an empty list
listA = []
# Append elements to the list
for n in range(4, 9):
   listA.append(n ** 3)
print("List using for loop:\n", listA)

Output

Running the above code gives us the following result −

List using for loop:
[64, 125, 216, 343, 512]

From another list

We can also create a list form another list by directly assigning elements to the new list.

Example

# Take a list
listA = [12,9,32,45]
#Given list
print("Given list:\n ",listA)
new_list = [n for n in listA if n % 3 == 0]
print("New List:\n", new_list)

Output

Running the above code gives us the following result −

Given list:
[12, 9, 32, 45]
New List:
[12, 9, 45]

Dictionary Comprehensions

A dictionary contains elements in form of pairs known as key-value pairs. In this article we will see how to create such dictionaries.

Using for loop and zip

We can take in two lists which can have keys and values. Then join them through comprehension to create a new dictionary.

Example

Day = ['Mon', 'Tue', 'Wed',]
Time= ['2pm','10am','11am']
# Create an empty dict
dictA = {}
# Use for loop
for (key, value) in zip(Day, Time):
   dictA[key] = value
print("Dictionary using for loop:\n",dictA)

Output

Running the above code gives us the following result −

Dictionary using for loop:
{'Mon': '2pm', 'Tue': '10am', 'Wed': '11am'}

Using key as index

In this case we take a Python list and uses elements as key for the dictionary. Also derive the values for each key using an expression.

Example

listA = [3,5,4,8,9,2]
dictA = {}
# Using for loop
for key in listA:
   if key % 2 != 0:
      dictA[key] = key ** 3
print("Dictionary using for loop:\n",dictA)

Output

Running the above code gives us the following result −

Dictionary using for loop:
{3: 27, 5: 125, 9: 729}

Set Comprehension

Python Set contains unique elements. It can be created in a similar manner as list.

With for loop

Here we take a list and apply a condition to fetch some elements from it. Then put those elements into to an empty set by using add method.

Example

listA = [12, 4, 25, 12,4,9]
setA = set()
# Using for loop
for x in listA:
   if x % 3 == 0:
      setA.add(x)
print("Set using for loop:", setA)

Output

Running the above code gives us the following result −

Set using for loop: {9, 12}

With for and in

In this method we directly use a for loop within {}. And assign the result into a set. Inside the follow we use elements from a list.

Example

listA = [12, 4, 25, 12,4,9]
# Using for loop
setA = {x for x in listA if x % 2 == 0}
print("Set using for loop:", setA)

Output

Running the above code gives us the following result −

Set using for loop: {12, 4}

Generator Comprehensions

In this approach we take the elements from a list and apply certain conditions on them and then put them into a for loop. The result is assigned to sequence. This method is called generator comprehension.

Example

listA = [12, 4, 25, 12,4,9]
genrtr = (var for var in listA if var % 2 == 0)
print("Values using generator comprehensions:\n")
for x in genrtr:
   print(x, end=',')

Output

Running the above code gives us the following result −

Values using generator comprehensions:
12,4,12,4,