Ad Code

How to Use Set Comprehension in Python

set comprehension


Python also allows for set comprehensions. As expected, you can't modify an existing set with a comprehension, only create a new one. Set comprehensions basically the purpose to create a new set

Set Comprehension in Python


Likewise, of course, the comprehension must result in a valid set. A set cannot contain multiple entries of the same value. Like the dictionary, Python is polite about this. 


If you try to add values to the set that are already there, it will replace the old one with the new one.

Curling brackets for set comprehension


  • Set comprehensions using the {} syntax only exist in Python 3. Before that, you'll have to use the set() function to create and work with sets.
  • You might guess, therefore, that one of the best uses of a set is to eliminate duplicates. 
  • In fact, this is one of the most basic forms of set comprehension. Given a list, we can duplicate it as a list with a simple list comprehension like this:

List logic


list_copy = [x for x in original_list]


It shouldn't surprise you, therefore, that if we change the list comprehension to a set comprehension, we get the same result, but as a set:

Set comprehension


my_list_with_dupes = [1,2,1,2,3,4,1,2,3,4,5,6,7,1,2,3] 
my_set_without_dupes = {x for x in my_list_with_dupes} 
print(my_set_without_dupes) 

{1, 2, 3, 4, 5, 6, 7}


Related posts

Post a Comment

0 Comments