Python Initialize Set

May 18, 2019
new_set = {1, 2, 3}

For empty set, use set(). {} is empty dict.

new_set = set()

Convert list to set

new_set = set([1, 2, 3])

Set comprehension

# odd number only
new_set = {x for x in [1, 2, 3, 4, 5] if x % 2}

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.