When it is required to extract elements from a List in a Set, a simple ‘for’ loop and a base condition can be used.
Example
Below is a demonstration of the same
my_list = [5, 7, 2, 7, 2, 4, 9, 8, 8] print("The list is :") print(my_list) search_set = {6, 2, 8} my_result = [] for element in my_list: if element in search_set: my_result.append(element) print("The result is :") print(my_result)
Output
The list is : [5, 7, 2, 7, 2, 4, 9, 8, 8] The result is : [2, 2, 8, 8]
Explanation
A list is defined and is displayed on the console.
Another set with specific elements is defined.
An empty list is defined.
The list is iterated over, and element is searched for in the ‘set’.
If it is found, it is added to the empty list.
This is the result that is displayed on the console.