Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Extract Elements from a List in a Set
When it is required to extract elements from a list that exist in a set, a simple 'for' loop with membership checking can be used. This technique filters the list to keep only elements that are present in the target set.
Method 1: Using For Loop
Below is a demonstration using a basic for loop with conditional checking ?
my_list = [5, 7, 2, 7, 2, 4, 9, 8, 8]
print("The list is:")
print(my_list)
search_set = {6, 2, 8}
print("The search set is:")
print(search_set)
my_result = []
for element in my_list:
if element in search_set:
my_result.append(element)
print("The result is:")
print(my_result)
The list is:
[5, 7, 2, 7, 2, 4, 9, 8, 8]
The search set is:
{8, 2, 6}
The result is:
[2, 2, 8, 8]
Method 2: Using List Comprehension
A more concise approach using list comprehension ?
my_list = [5, 7, 2, 7, 2, 4, 9, 8, 8]
search_set = {6, 2, 8}
result = [element for element in my_list if element in search_set]
print("Original list:", my_list)
print("Search set:", search_set)
print("Filtered result:", result)
Original list: [5, 7, 2, 7, 2, 4, 9, 8, 8]
Search set: {8, 2, 6}
Filtered result: [2, 2, 8, 8]
Method 3: Using filter() Function
Using the built-in filter() function with a lambda expression ?
my_list = [5, 7, 2, 7, 2, 4, 9, 8, 8]
search_set = {6, 2, 8}
result = list(filter(lambda x: x in search_set, my_list))
print("Original list:", my_list)
print("Search set:", search_set)
print("Filtered result:", result)
Original list: [5, 7, 2, 7, 2, 4, 9, 8, 8]
Search set: {8, 2, 6}
Filtered result: [2, 2, 8, 8]
How It Works
A list with duplicate elements is defined and displayed on the console.
A set containing target elements is created for membership testing.
Each method iterates through the list and checks if elements exist in the set.
Matching elements are collected while preserving their original order and duplicates.
The `in` operator provides O(1) average lookup time for sets, making it efficient.
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| For Loop | High | Good | Beginners, complex logic |
| List Comprehension | Medium | Better | Concise, readable code |
| filter() | Medium | Good | Functional programming style |
Conclusion
Use list comprehension for concise and readable code when extracting elements from a list based on set membership. The `in` operator with sets provides efficient O(1) lookup time, making these approaches suitable for large datasets.
