Having Covered Frozenset and set in python with example, we will now learn about python program to get element from set without removal i.e. how to retrieve element from set without removing it in python ?
Getting Started
The task is to get an element from set without removing that item from set. For example,
fruitList = {"Apple", "Banana", "Guava", "Jackfruit", "Papaya", "Orange"}
Now, we want to get any element from above python set i.e. “Apple” or “Banana” or any other item from fruitList.
We can do so in many ways –
- Using For Loop
- Using iter and next
- Using List Index
- Using Pop and Add
- Using Random Sample
- Using Set Unpacking
Using For Loop
We can use for loop in python to find next item in set without item removal as below –
fruitList = {"Apple", "Banana", "Guava", "Jackfruit", "Papaya", "Orange"} for e in fruitList: break print(e)
Output:
Apple
In above example,
– We run a for loop and print the first element in set.
Using Using iter and next
We can also write python program to get element from set without removal using iter() and next() built-in functions in python as shown below –
fruitList = {"Apple", "Banana", "Guava", "Jackfruit", "Papaya", "Orange"} e = next(iter(fruitList)) print(e)
Output:
Jackfruit
iter() iterates the set and next() return the next element.
Using List Index
List indexing can also be used to get element from set. In this approach, a new list is created from set. So, If set it too large, it can become very slow because a large list will be created in this approach.
fruitList = {"Apple", "Banana", "Guava", "Jackfruit", "Papaya", "Orange"} e = list(fruitList)[0] print(e)
Output:
Apple
Using Pop and Add
pop() method pops an element from the set. It means that element will be removed from set. So, we need to add it back to maintain all the items in set. That’s why we also need to use add() method. Thus, we can write python program to get element from set without removal using pop() and add(). For example,
fruitList = {"Apple", "Banana", "Guava", "Jackfruit", "Papaya", "Orange"} e = fruitList.pop() fruitList.add(e) print(e)
Output:
Guava
Using Random Sample
Using random sample, we can get single element from set without removing that item. For example,
import random fruitList = {"Apple", "Banana", "Guava", "Jackfruit", "Papaya", "Orange"} e = random.sample(fruitList, 1) print(e)
Output:
['Guava']
Note that item is returned as list.
Using Set Unpacking
Python Set unpacking technique can also be used to get element from set without removing that item. So, we can write program python to get element from set as shown below –
fruitList = {"Apple", "Banana", "Guava", "Jackfruit", "Papaya", "Orange"} e = [*fruitList][0] print(e)
Output:
Banana
Which Approach is Better ?
Each of the above mentioned approach is better that other in certain types of set. So, how to choose which one is better. Let’s take a look at the time complexity when size of the set increases –
You must be logged in to post a comment.