Retrieve elements from Python Set
Prerequisites: Python Set
In this article, we will discuss how to retrieve elements from the sets in Python.
Example 1: Get all elements using for loop
By iterating the elements in a set using for loop we can get them all set elements.
Example:
Python3
# create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076}# display set elements using for loopfor i in data: print(i)print("----")# create a set with string elementsdata1 = {"sravan", "harsha", "jyothika"}# display set elements using for loopfor i in data1: print(i) |
Output:
7072 7074 7076 7058 7059 ---- sravan harsha jyothika
Example 2: Access particular elements using index
In set we can not perform indexing, first, we have to convert that set into a list and then perform the indexing. So we are using list() function to convert the set into the list.
Example:
Python3
# create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076}# retrieve 1 st elementprint(list(data)[0])# retrieve 4 th elementprint(list(data)[3])# retrieve last elementprint(list(data)[-1]) |
Output:
7072 7058 7059
Example 3: Retrieve the last element
We can convert it into a list and then access the last element by using pop() function. This will get the last element or we can also use index = -1 to get the last element.
Example:
Python3
# create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076}# retrieve last elementprint(list(data)[-1])# retrieve last elementprint(list(data).pop()) |
Output:
7076 7076
Example 4: Access first element
We can access the first item in the set by using iter() function, we have to apply next() to it to get the first element.
Syntax: next(iter(set))
Example:
Python3
# create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076}# retrieve first elementprint(next(iter(data))) |
Output:
7058
We can also use first() method from the iteration_utilities module, Which will return the first element.
Syntax: first(set)
Example:
Python3
# import iteration_utilitiesfrom iteration_utilities import first# create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076}# retrieve first elementprint(first(data)) |
Output:
7058
Example 5: Retrieve Random elements
We can get n number of random elements from a set using sample() function. This is available in a random module and this will return a list of sample elements.
Example:
Python3
# import random moduleimport random# create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076}# retrieve 2 random elementsprint(random.sample(data, 2))# retrieve 1 random elementprint(random.sample(data, 1))# retrieve 4 random elementsprint(random.sample(data, 4)) |
Output:
[7058, 7074] [7072] [7059, 7074, 7058, 7076]



.png)