FANDOM


What is a set? Edit

A set is a collection of items which is unordered and unindexed. They are defined using curly braces:

some_set = {"thing01", "thing02", "thing03"}

Or you can build a set using the set constructor:

some_set = set(("thing01", "thing02", "thing03"))

# Note the rounded braces used here instead of the curly braces.


You can have different types in a single set too, like so:

some_set = {12, "thing"} 

Accessing itemsEdit

Unlike lists you can not asscess items in a set using indexing, because sets are unordered and have no indexes.

for thing in set_of_things:
  print(thing)

But you can loop through a set with a for-loop, or ask if a specific item exists in the set by using the in  keyword:

set_of_things = {"Bulbasaur", 1, "Grass"}
print("Grass" in set_of_things)

# This will return 'True'


Changing itemsEdit

Once a set is created, you cannot change the items inside it. But you CAN add new ones.


Adding itemsEdit

To add a new item to a set we need to use the add() method.

To add more than one item to a set we need to use the update() method.

set_of_things = {"Bulbasaur", 1, "Grass"}
set_of_things.add("Cute")

set_of_things.update(["Lettuce Boi", "Grass Baby", "Onion Frog"])


Removing itemsEdit

To remove an item in a set we can use either the remove() or the discard()  method.

set_of_things.remove("Onion Frog")
set_of_things.discard(1)


You can also use the pop() method to remove the last item in the list, however this isn't ideal in the case of sets as sets so not have any order, so you won't necessarily know what you are removing.


Empty the setEdit

To empty/clear the set you can use the clear()  method:

set_of_things.clear()


If you want to delete the set entirely you can use the del() keyword:

del set_of_things


Getting the length of a setEdit

We can determine how many items are in a set by using the len() method. Same as we use for strings and lists.

print(len(set_of_things))


ReferencesEdit

Python Sets - w3Schools.com

Community content is available under CC-BY-SA unless otherwise noted.