
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Extract Elements from a List in a Set using Python
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.
Advertisements