In our earlier posts (Part 1 and Part 2) , we discussed extensively on list comprehension. In this post, I would like to conclude these ideas and see how we can extend it to other iterables in Python. A set comprehension works in a similar fashion. A set data structure in Python stores unique elements. Let's create a list of numbers
list_nos = [1,2,3,4,4,4,5,6,6,2,2,2,1,1,0]
We create a set using set comprehension as below.
set_nos = {element for element in list_nos}
print(set_nos)
---> {0, 1, 2, 3, 4, 5, 6}
Another example of a set comprehension can be seen below. Let's create a sentence or rather a string in Python.
sentence = "I am having a great day"
set_sentence = {element for element in sentence}
print(set_sentence)
---> {'t', 'e', 'h', 'I', 'm', 'v', 'y', ' ', 'n', 'g', 'a', 'd', 'i', 'r'}
List comprehension can be extended to dictionaries as well in Python. Let's create a list of strings.
list_strings = ["Hi", "Hello", "Wait", "Dry"]
dict_comprehension = {key:value for key,value in enumerate(list_strings)}
print(dict_comprehension)
---> {0: 'Hi', 1: 'Hello', 2: 'Wait', 3: 'Dry'}
In a dictionary comprehension, we enclose the expression in a "{ }" just like in a
set. However, the only difference is, a dictionary has a key value pair while a
set has only elements.
In general, list comprehension is widely used and is very popular. Set and dictionary comprehension are not so popular, but we must be aware of it.
Comments
Post a Comment