Hurry! Try our new Interactive Courses for FREE. 🥳   🚀
  Signup/Sign In

How to access elements in a Set

In this article, we will learn to access elements in a set in Python. We will use some built-in functions, some simple approaches, and some custom codes as well to better understand the topic. Let's first have a quick look over what is a set in Python.

Python Sets

Python Set is a built-in data type. It is a collection of unordered data values. An unordered dataset leads to unindexed values. Set values cannot be accessed using index numbers as we did in the list. Set values are immutable which means we cannot alter the values after their creation. Data inside the set can be of any type say, integer, string, or float value. For example,

set1 = {"Ram", "Arun", "Kiran"}
set2 = {16, 78, 32, 67}
set3 = {"apple", "mango", 16, "cherry", 3}

Access Elements of a Set

Reading elements of a set in Python basically means accessing one or multiple elements of the set. We know that set values are unordered which means the user is not sure of the order in which data values appear. Therefore, it is unindexed. We cannot access the elements of a set using an index say, set[0]. It will not print the 0th index value, instead, it will return an error. In this article, we will learn to access one or more elements and observe the following outputs.

Let us look at the below examples and learn what are the different ways to read elements of a given set.

  1. Using loop and "in" operator
  2. Using "iter" and "next" keyword

Example: Accessing Using a loop and in operator

This example uses a loop to iterate over the elements of a set and checks for elements using in operator. As the set does not have indexes, we can access elements using a loop and perform operations over it.

#input set
set1 = {4, 6, 12, 11, 3, 5}

#Access element using for loop
print("\nReading elements of the set: ")

for x in set1:
      print(x)


Reading elements of the set:
3
4
5
6
11
12

Example: Accessing Using in Operator

To check for a specified value in a set, we can use the in operator. It will return True if that value is in the set else it will return False.

#input set
set1 = {"apple", "mango", "cherry", "pear", "guava"}

#check for an element
print("apple" in set1)
print("watermelon" in set1)


True
False

Example: Accessing Using iter and next keyword

This method uses iter to create an iterator object and with the help of next(), it prints the first item of the given input set.

#input set
set1 = {1, 2, 3, 4, 5}
 
x = next(iter(set1))
#prints first item
print(x)
 


1

Note: Generally, the set is converted to a list using the list keyword list(set), and then the reading of set items takes place.

Conclusion

In this article, we learned to read elements of a set by using a loop, in operator, and keywords like next and iter. We used some custom codes as well. We learned that set is an unindexed data type and does not access elements using the index.