Python Set comprehension - How to Use it Read now

set comprehension

Set comprehension in Python will not allow duplicates.

You can't modify an existing set with a comprehension. But you can create a new one. Set comprehension the prime purpose is to create new set.

Set Comprehension 

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- 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

if we change the list comprehension to a set comprehension, we get the same result, but as a set. That means without duplicates.

list_copy = [x for x in original_list]


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} 

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

Related posts

Post a Comment

Thanks for your message. We will get back you.

Previous Post Next Post