## Overview

A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

*Set* in Python is a data structure equivalent to sets in mathematics. It may consist of various elements; the order of elements in a set is undefined. You can add and delete elements of a set, you can iterate the elements of the set, you can perform standard operations on sets (union, intersection, difference). Besides that, you can check if an element belongs to a set.

Unlike arrays, where the elements are stored as ordered list, the order of elements in a set is undefined (moreover, the set elements are usually not stored in order of appearance in the set; this allows checking if an element belongs to a set faster than just going through all the elements of the set).

Any immutable data type can be an element of a set: a number, a string, a tuple. Mutable (changeable) data types cannot be elements of the set. In particular, list cannot be an element of a set (but tuple can), and another set cannot be an element of a set. The requirement of immutability follows from the way how do computers represent sets in memory.

### Initializing a set

There are two ways to create sets: using curly braces `{}`

and the bult-in function `set() `

`>>> s = set([1, 2, 3])`

>>> s = {1, 2, 3}

### Operations with elements

You can get the number of elements in the set using the function `len`

.

you can check whether an element belongs to a set using the keyword `in`

: expressions like `a in A`

return a value of type `bool`

. Similarly there's the opposite operation `not in`

. To add an element to the set there is the method `add`

:

```
A = {1, 2, 3}
print(1 in A, 4 not in A)
A.add(4)
```

There are two methods to remove an element from a set: `discard`

and `remove`

. Their behavior varies only in case if the deleted item was not in the set. In this case the method `discard`

does nothing and the method `remove`

throws exception `KeyError`

.

Finally, `pop`

removes one random element from the set and returns its value. If the set is empty, `pop`

generates the exception `KeyError`

.

You can transform a set to list using the function `list`

.

Categories: #Python Tags: #Python #Data Structures #Statistics #Mathematics #Lists