Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python set() Function

Python set() Function

Python3 Built-in Functions Python3 built-in function


set() is a built-in function in Python used to create a mutable set.

A set is an unordered collection of unique elements, similar to the mathematical concept of a set.set() The function can create a set from other iterables and is often used for deduplication, set operations and similar scenarios.

Word meaning: set means "set" and refers to an unordered collection of unique elements in Python.


Basic syntax and parameters

Syntax format


set(iterable)

Parameter Description

- Type: iterable - Description: the iterable to convert into a set.

Function description


Example

Example 1: creating sets

Example

Create from a list (automatically deduplicated)

lst

=

[

1

,

2

,

2

,

3

,

3

,

3

,

4

]

s

=

set

(

lst

)

print

(

s

)

       

Output: {1, 2, 3, 4}

Create from a string

s

=

set

(

"hello"

)

print

(

s

)

       

Output: {'h', 'e', 'l', 'o'}

Create from a tuple

t

=

(

1

,

2

,

3

,

2

,

1

)

s

=

set

(

t

)

print

(

s

)

       

Output: {1, 2, 3}

Create from a dictionary (keys only)

d

=

{

"a"

:

1

,

"b"

:

2

,

"c"

:

3

}

s

=

set

(

d

)

print

(

s

)

       

Output: {'a', 'b', 'c'}

Empty Collection

s

=

set

(

)

print

(

s

)

       

Output: set()

print

(

type

(

s

)

)

 

Output:

Expected output:

{1, 2, 3, 4}
{'h', 'e', 'l', 'o'}
{1, 2, 3}
{'a', 'b', 'c'}
set()

Code analysis:

  1. A set automatically removes duplicate elements.
  2. Sets are unordered, so the element order may vary.
  3. Note:{} creates an empty dictionary, not an empty set.

Example 2: set operations

Example

Create two sets

A

=

{

1

,

2

,

3

,

4

}

B

=

{

3

,

4

,

5

,

6

}

Union

print

(

A | B

)

     

Output: {1, 2, 3, 4, 5, 6}

print

(

A.

union

(

B

)

)

Output: {1, 2, 3, 4, 5, 6}

Intersection

print

(

A & B

)

     

Output: {3, 4}

print

(

A.

intersection

(

B

)

)

 

Output: {3, 4}

Difference (A - B)

print

(

A - B

)

     

Output: {1, 2}

print

(

A.

difference

(

B

)

)

 

Output: {1, 2}

Symmetric difference

print

(

A ^ B

)

     

Output: {1, 2, 5, 6}

print

(

A.

symmetric_difference

(

B

)

)

 

Output: {1, 2, 5, 6}

Expected output:

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

Sets support rich operations: union, intersection, difference and symmetric difference.


Python3 Built-in Functions Python3 built-in function