What are sets in Python?

What is a set?

A set is an unordered and unindexed “bag” of unique values.

A single set can contain values of any immutable datatype which means the values can’t be changed. A set itself is a mutable object i.e, an object that can be changed after it is created.

Creating a set

Let’s learn how to create a set.

a_set = {'alpha', 'bravo', 'charlie'}
print (a_set)
#A set can also be created using the built-in set() function
#set() takes a "list" as argument and converts it to a set
my_set = set([1,2,3,4,5])
print (my_set)

Accessing items

Sets are unindexed, hence you cannot access items in a set by referring to an index. What you can do is loop through the set in order to get a specific value.

a_set = {'alpha', 'bravo', 'charlie'}
for item in a_set:
print (item)

Note: Sets are unordered, so the items will appear in a random order.

Methods

Python has a set of built-in methods that you can use on sets. Some of them are specified below:

  • Add items: Once a set is created, you cannot change its items, but you can add new items. To add one item to a set, use the add() method and to add more than one item to a set, use the update() method.

  • Remove items: To remove an item in a set, use the remove() method. You can also use the discard() method for removing.

a_set = {'alpha', 'bravo', 'charlie'}
print ("Adding value to set")
a_set.add('jenny')
print(a_set)
a_set.update(['matty', 'johny'])
print ("Updating values in set")
print(a_set)
print ("Removing value from set")
a_set.remove('matty') #If the item to remove does not exist, `remove()` will raise an error.
print(a_set)
print ("Discarding value from set")
a_set.discard('johny') #If the item to remove does not exist, `discard()` will **NOT** raise an error.
print(a_set)
  • Length of set: The len() method can be used to determine the count of items in a set.

  • Clear set: The clear() method empties the set.

a_set = {'alpha', 'bravo', 'charlie'}
print ("Number of items are: ", (len(a_set)))
a_set.clear()
print("set cleared")
print(a_set)

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved