Access Set Elements Python

Access Set Elements Python

Now, we are going to learn about how we can access the set elements here. Basically, we are now familiar with the fact, that a set is unordered, unindexed, and unchangeable. When we access individual elements from a list or tuple, we make use of the indexes. But here, we do not have any kind of indexes, to access the individual set elements. Also, we are not sure about the order of the elements in the set.

So, it is clear that we cannot access the items in the set using some index, or some key. But here, we can loop through our set using the for a loop. Also, we can make use of some membership operator, to check the membership of some element in the set.

Access Set Elements Python

So, now Let’s have a look at how we can loop through the set, using the for loop, and accessing the different set elements. Let’s have a look at a program, which demonstrates the same thing

As you can see, in the above program, we have a simple set, which has some elements. Here, we are trying to loop through the set. Let’s have a look at the output of the above program.

True

3.2

12

29

GyaniPandit

31

As you can see, we were able to access the set by looping through the set. But here as well, making changes to the element variable, does not mean that we are making changes to the set element.

Also, we can also use the membership operators, to check the membership of some elements in the set. Let’s have a look at a simple example, which tries to demonstrate the same thing.

As you can see, we are using the membership operators, to check the membership of some elements in the set. First of all, we are checking that is there the string ‘GyaniPandit’ in the set. The answer to this is simply True since the string ‘GyaniPandit’ is there in the set. Also, after that, we are checking that is 10 not there in the mySet? The clear answer to this is clearly True since 10 is not there in the set.

So, this way, we can access the set elements, looping through the list, or check the membership of some element in the set.