Python SET Comprehension With Examples
Rushikesh J.
Software Test Engineer @Vinz Global | Robot Framework | Manual Testing, Automation Testing | Python | Selenium | GIT | JIRA | Immediate Joiner | API Testing Using Postman | Jenkins
What is Comprehension?
?We create a sequence from a given sequence is called comprehension.
?Sequence means list, tuple, string and range.
?We can also create a new dictionary from existing dictionary.
?Some sequence allow comprehension but some not.
Why need of Comprehension?
?Simple way to create new sequence
?Filtering & Searching
?One line of code
?Fastest way
?Python set comprehension means, creating a new set from another iterabel object like list, range function etc.
?On the basis of condition we can create a new set from created (given) set or other iterable object.
?We can filter a old set to get required elements / items to store in a new set.
?It is fastest way and one line code to create new set from given set on the basis of some condition.
Syntax
newSet = {expression for item/element in sequence}
SET Comprehension Syntax
newSet = {expression for item/element in sequence}
newSet = {expression for item/element in sequence if statement}
newSet = {expression if statement else statement for item/element in sequence}
newSet = {expression for item/element in sequence nested if statement}
SET Comprehension Example
Examples
lst = [3, 1, 5, 6, 7, 8, 9, 0]
set1 = {x+1 for x in lst } # simple
lst = [‘yellow', ‘pink', ‘gray', ‘white', ‘black']
new_set2 = {x for x in names if ‘a' in x} # if statement
set3 = {“even" if i%2==0 else “odd" for i in range(20)} # if else statement
set4 = {x for x in range(50) if x % 2 == 0 if x % 5 == 0} # nested if statement