Home > Backend Development > Python Tutorial > A brief explanation of set collections in Python (with examples)

A brief explanation of set collections in Python (with examples)

不言
Release: 2018-09-25 17:10:06
Original
2414 people have browsed it

This article brings you a simple explanation of set collections in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The set collection uses {} to save a set of iterable objects, such as lists, strings, and the set collection itself. If there are duplicate elements in the set, the duplicate elements will be automatically removed

a=set([1,2,3])
print(a)
b=set('hello python')
print(b)
c=set({1,2,3})
print(c)
d=set({'hello python'})
print(type({'hello '}))
print(d)
Copy after login

Display results

 {1, 2, 3}
 {'h', 'l', 'e', ' ', 'p', 'n', 'y', 'o', 't'}
 {1, 2, 3}
 <class &#39;set&#39;>
 {&#39;hello python&#39;}
Copy after login

Assume a=set( [1,2,3])
add After adding an element to the set collection, replace the original object a.add( 4) print(a) output {1, 2, 3, 4}
remove After removing an element from the set collection, replace the original object. If If the replaced element is not in the set collection, an error will be reported

a.remove(2) print(a) output

{1,3}

Little knowledge points: set collection can be seen as It is a mathematically unordered and non-repeating set of elements, so the intersection and union in the mathematical sense can be done between the two sets

##a&bOutput result{1,3}a |bOutput result{1,2,3,4}
Assume a=set([1,2,3] ) b=set([1,3])

The above is the detailed content of A brief explanation of set collections in Python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template