In this tutorial, I will define what Python sets are, how to measure the size of sets in Python, how to add or remove elements in a set, and how to loop through a set. I will also explain why sets are not subscriptable in Python.
Definition
What is a set in Python? A set is an unordered list of immutable elements. That suggests:
- Elements in a set are unordered. This is different from lists, which are ordered.
- Elements in a set are unique. That is, a set doesn’t allow duplicate elements.
To define a set, you use the curly brace {}
.
cars={"Tesla", "Ford", "Toyota"}
print(cars)
After running the code above, you will get the following output.
{'Toyota', 'Tesla', 'Ford'}
Set Size
The following code shows how you can measure the size of a set in Python. You can use len() to ask Python to return the number of elements in a set.
cars={"Tesla", "Ford", "Toyota"}
print(len(cars))
After running the code above, you will get the following output.
3
Check Elements
The following code shows how you can check whether an element is in a set in Python. In particular, you can use the if statement to see whether an element is included in the set and then return an output.
cars={"Tesla", "Ford", "Toyota"}
brand='Tesla'
if brand in cars:
print(f'The set contains {brand}.')
After running the code above, you will get the following output.
The set contains Tesla.
Add and Remove Elements
Now you know how to check elements, but how you can change elements in a set. The following shows how you can add and remove elements in a set in Python.
cars={"Tesla", "Ford", "Toyota"}
brand_to_add='Lucid'
cars.add(brand_to_add)
print(cars)
cars.remove('Ford')
print(cars)
Output:
{'Ford', 'Tesla', 'Lucid', 'Toyota'} {'Tesla', 'Lucid', 'Toyota'}
Looping through Elements
How you can print elements one by one in a set? One of the solutions is to use the for statement. The following code shows how you can print out elements in a set.
cars={"Tesla", "Ford", "Toyota"}
print(cars)
for car in cars:
print(car)
Output:
{'Tesla', 'Toyota', 'Ford'} Tesla Toyota Ford
‘Set’ object is not subscriptable
As per Python’s Official Documentation, a set is an Unordered Collections of Unique Elements. Since it is unordered, sets don’t support operations like indexing or slicing, etc. The following code tries to print out the first element in the set of “cars.” However, you see that the output shows an error message saying that ‘set’ object is not subscriptable.
cars={"Tesla", "Ford", "Toyota"}
print(cars[0])
TypeError: 'set' object is not subscriptable