Python Set Usage Example

June 5, 2019

Initialize Sets

items = {1, 2, 3}

or

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

Add to Sets

Add values

items.add(4)

Add sets to sets

items.update({5, 6})

Add list to sets

items.update([7, 8])

Check value in sets

if 5 in items:
    pass

Remove values from sets

Remove value

items.remove(8)

Remove sets from sets

items.difference_update({6, 7})

Remove list from sets

items.difference_update([4, 5])

Convert sets to list

list_items = list(items)

References:

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