Access items of Python sets

In Sets, we are not able to access the items using the set indexes, as Set is a collection that is unordered and also has the unordered index i.e there are no fix indexes for the items of the set. So there is no way to access the item using indexes as in Python lists.

But there is a way to see or access all of the items of a set or checking for the particular item whether it is present or not in a particular set, The following are the two methods, have a look at them.

Accessing Python set elements

Using ‘for’ loop:
We can apply ‘for’ loop through the set and print all the values of the sets.
Let’s have a look at an example below:

vegetables ={'spinach','carrot','onion','potato'}
for i in vegetables:
  print(i)

Output:

potato
onion
carrot
spinach

So this is how we are able to access the set items using for loop

Using ‘in’ keyword :
We can check the item name by specifying its name and using ‘in’ keyword. If the specified item name is present in the set the output returned will be a boolean value in True either the returned output will be false. Let’s have a look at an example
Checking if ‘spinach’ is present in the vegetable set :

vegetables ={'spinach','carrot','onion','potato'}
print('spinach' in vegetables)

Output:

True

So output returned here is True, because the ‘spinach’ is the part of the vegetables set.

Also, read: Add items to Python sets

Hope this might help.
Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *