10 things you should know about Sets in Python

栏目: IT技术 · 发布时间: 4年前

内容简介:AThe following code block shows two sets, containing a collection of numbers and cities.Any immutable data type can be an element of a set (e.g. strings and integers). If you try to use a mutable data type inside a set, an exception (

10 things you should know about Sets in Python

1. What is a Python set?

A set is an unordered and mutable collection of unique elements. Sets are written with curly brackets ( {} ), being the elements separated by commas.

The following code block shows two sets, containing a collection of numbers and cities.

Any immutable data type can be an element of a set (e.g. strings and integers). If you try to use a mutable data type inside a set, an exception ( TypeError ) is raised, as shown below.

2. Create a set with set() constructor

Setscan also be defined with the built-in function set([iterable]) . This function takes as argument an iterable (i.e. any type of sequence, collection, or iterator), returning a set that contains unique items from the input (duplicated values are removed).

As shown above, the original order of the input items is not maintained, since sets are unordered containers.

We can also use the set() constructor without any input parameter. In this case, the constructor returns an empty set .

3. Add an element to a set

To add an element to a set , we use the set.add(element) method. This method modifies the set in-place, returning None .

As shown below, the .add() method does not add an element to the set if the element is already present, since sets cannot contain duplicated items.

Unlike with lists, we cannot insert an element at a given index, since sets are unordered containers, meaning elements have not a particular position inside a set .

4. Remove an element from a set

There are three ways of removing elements from a set:

  • Using the set.remove(x) method
  • Using the set.discard(x) method
  • Using the set.pop() method

The remove method

The set.remove(x) method removes an element x from a set. This method modifies the set in-place, returning None . If the element x does not exist, an exception ( KeyError ) is raised.

The discard method

The set.discard(x) method removes an element x from a set if it is present. In comparison to the remove method , the discard method does not raise an exception ( KeyError ) if the element to be removed does not exist.

As shown above, the discard method modifies the set in-place, returning None .

The pop method

The set.pop() method removes and returns an arbitrary element from a set.

In comparison to lists , the pop method does not take any arguments. We can not specify the index we want to remove, since sets are an unordered collection of elements.

5. Mathematical operations: union, intersection, difference, and symmetric difference

We can use sets in Python to compute mathematical operations such as union , intersection , difference , and symmetric difference . These logical operations can be represented with a diagram called Venn diagram . Venn diagrams are widely used in mathematics, statistics, and computer science to visualize differences and similarities between sets. We can plot area-weighted two- and three-circle Venn diagrams with the third-party library matplotlib-venn.

Given two sets, one containing animals that are mammals and another one containing aquatic animals.

We can compute the aforementioned mathematical operations in the following manner.

Union

The union of two sets A and B is the set containing the elements that are in A , B , or both , and is denoted by A ∪ B .

The red shaded area of the Venn diagram represents the union of the sets mammals and aquatic.

Union of two sets

To compute this operation with Python , we can use either the set.union(another set) method or the | operator.

union of two sets

As shown above, both return a new set containing all items from sets mammals and aquatic.

Intersection

The intersection of two sets A and B is the set containing the elements that are common to both sets and is denoted by A ∩ B .

The red shaded area of the Venn diagram represents the intersection of the sets mammals and aquatic.

Intersection of two sets

In Python, we can compute the intersection of two sets using either the set.intersection(another set) method or the & operator.

As you can observe, the intersection method and the & operator return a new set, containing the items that exist in both sets without modifying them.

Difference

The difference of two sets A and B is the set of all elements of set A that are not contained in set B and is denoted by A-B .

The red shaded area of the Venn diagram represents the difference between mammals and aquatic (mammals-aquatic). This set contains the animals that are mammals but not aquatic.

Difference of mammals minus aquatic

We can also obtain the animals that are aquatic but not mammals, calculating the difference between aquatic and mammals.

Difference of aquatic minus mammals

To compute the difference between two sets in Python, we can use either the set.difference(another set) method (set-other set) or the ( ) operator.

As you can observe, the sets mammals and aquatic are not modified in-place.

Symmetric difference

The symmetric difference of two sets A and B is the set of elements that are in either of the sets A and B , but not in both, and is denoted by A △ B.

The following Venn diagram represents the symmetric difference of the sets mammals and aquatic (red shaded area). This set contains the animals that are mammals and aquatic but not both.

Symmetric Difference of two sets

In Python, we can find the symmetric difference of two sets using either the set.symmetric_difference(another set) method or the ^ operator as follows.

6. Subsets and supersets

A set A is a subset of a set B (A ⊆ B) or equivalently set B is a superset of set A (B ⊇ A), if all elements of set A are contained in set B .

The following Venn diagram represents two sets mammals and aquatic_mammals , being aquatic_mammals a subset of mammals .

To check whether set A is a subset/superset of set B , we can use the following methods:

  • A.issubset(B) → This method returns True if all elements of set A are contained in set B.
  • A.issuperset(B) → This method returns True if all elements of set B are contained in set A .

The following code block uses both methods to check if a set is a subset/superset of another set.

7. Disjoint

Two sets are disjoint if they have no elements in common. The following two sets mammals and reptiles are disjoint sets as their intersection is an empty set .

We can check if two sets are disjoint using the set.isdisjoint(another set) method. This method returns True if both sets have no elements in common. If they have, it returns False .

8. Check if an element exists in a set

To check whether an element exists in a set , we have to use a membership operator . Membership operators are used to test whether an element is present in a sequence (e.g. strings, lists, tuples, sets, or dictionaries). There are two membership operators, as explained below.

  • in → Evaluates to True if the object on the left side is included in the object on the right side.
  • not in → Evaluates to True if the object on the left side is not included in the object on the right side.

9. Find the length of a set

To determine how many elements the set contains, we can use the len() function. This function returns the number of items of an object. The input of the function can be not only a set, but also another type of sequence such as a string, dictionary, list, or tuple.

10. Alternative container: frozenset

A frozenset object is a set that, once created, cannot be changed. We create a frozenset in Python using the frozenset([iterable]) constructor, providing an iterable as input.

Since frozensets are immutable, they do not accept the methods that modify sets in-place such as add , pop , or remove . As shown below, trying to add an element to a frozenset raises an exception ( AttributeError ).

Unlike sets, frozensets can be used as keys in a dictionary or as elements of another set.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

打火机与公主裙·荒草园

打火机与公主裙·荒草园

Twentine / 青岛出版社 / 2017-3 / 36.00元

“如果人临死前真有走马灯这个环节,她大概会是我这辈子见的最后一人。” 从青涩的校园时代里一抹明亮的金,到厮杀的职场中那化不开的黑,李峋就像荒芜之地的一株野草,受到再大的挫折依然固执地生长。 如果说朱韵从前的生活一直维持着表面的顺风顺水,平静安和,那李峋的出现则打破了这一切。他是她生命中第一次,也是唯一一次的冒险。 在外人眼里李峋嚣张而轻蔑,只有朱韵懂得他心中那片自留地,自愿成为孤......一起来看看 《打火机与公主裙·荒草园》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码