Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is '+' not understood by Python sets?

Tags:

python

set

I would like to know why this is valid:

set(range(10)) - set(range(5)) 

but this is not valid:

set(range(10)) + set(range(5)) 

Is it because '+' could mean both intersection and union?

like image 623
badzil Avatar asked Oct 07 '11 20:10

badzil


People also ask

Do sets exist in Python?

In Python, a Set is an unordered collection of data types that is iterable, mutable and has no duplicate elements. The order of elements in a set is undefined though it may consist of various elements.

What is unique about sets in Python?

Every set element is unique (no duplicates) and must be immutable (cannot be changed). However, a set itself is mutable. We can add or remove items from it. Sets can also be used to perform mathematical set operations like union, intersection, symmetric difference, etc.

Are sets better than lists Python?

Lists are slightly faster than sets when you just want to iterate over the values. Sets, however, are significantly faster than lists if you want to check if an item is contained within it. They can only contain unique items though.

Why do sets exist in Python?

Grouping objects into a set can be useful in programming as well, and Python provides a built-in set type to do so. Sets are distinguished from other object types by the unique operations that can be performed on them.


1 Answers

Python sets don't have an implementation for the + operator.

You can use | for set union and & for set intersection.

Sets do implement - as set difference. You can also use ^ for symmetric set difference (i.e., it will return a new set with only the objects that appear in one set but do not appear in both sets).

like image 187
Platinum Azure Avatar answered Oct 11 '22 05:10

Platinum Azure