Open In App

Python Program to Extract Elements from list in set

Improve
Improve
Like Article
Like
Save
Share
Report

Given a list, the task is to write a Python Program to extract all the elements with its occurrence matching in the set.

Input : test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9], search_set = {6, 2, 8}
Output : [6, 2, 2, 6, 8]
Explanation : 2, 6 occur twice and in order with respect to other elements is output.

Input : test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9], search_set = {8, 3, 5}
Output : [5, 3, 5, 8]
Explanation : 5 occurs twice and in order with respect to other elements is output.

Method #1 : Using loop

In this, each list element is iterated and checked for its presence in set using in operator and appended to the result if found. 

Python3




# Python3 code to demonstrate working of
# Elements from list in set
# Using loop
 
# initializing list
test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]
              
# printing original list
print("The original list is : " + str(test_list))
 
# initializing search set
search_set = {6, 2, 8}
 
res = []
for ele in test_list:
     
    # check if element is present in set
    if ele in search_set:
        res.append(ele)
 
# printing result
print("Set present list elements : " + str(res))


Output

The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [6, 2, 2, 6, 8]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2 : Using repeat() + from_iterable() + count()

In this, we test for each set element in list and repeat using repeat() by the count required to be computed using count(). The order is not maintained in this result.

Python3




# Python3 code to demonstrate working of
# Elements from list in set
# Using repeat() + from_iterable() + count()
from itertools import chain, repeat
 
# initializing list
test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]
              
# printing original list
print("The original list is : " + str(test_list))
 
# initializing search set
search_set = {6, 2, 8}
 
# repeat repeats all the occurrences of elements
res = list(chain.from_iterable((repeat(ele, test_list.count(ele))
                                for ele in search_set)))
 
# printing result
print("Set present list elements : " + str(res))


Time Complexity: O(n)

Space Complexity: O(n)

Method #3: Using Counter() function

Python3




# Python3 code to demonstrate working of
# Elements from list in set
from collections import Counter
# initializing list
test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]
 
# printing original list
print("The original list is : " + str(test_list))
result = []
# initializing search set
search_set = {6, 2, 8}
freq_set = Counter(search_set)
for i in test_list:
    if i in freq_set.keys():
        result.append(i)
# printing result
print("Set present list elements : " + str(result))


Output

The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [6, 2, 2, 6, 8]

Time complexity: O(n), where n is the length of the test_list. The Counter() takes O(n) time
Auxiliary Space: O(n), extra space of size n is required

Method #4 : Using repeat() + from_iterable() + operator.countOf()

In this, we test for each set element in list and repeat using repeat() by the count required to be computed using operator.countOf(). The order is not maintained in this result.

Python3




# Python3 code to demonstrate working of
# Elements from list in set
# Using repeat() + from_iterable() + operator.countOf()
from itertools import chain, repeat
import operator as op
 
# initializing list
test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]
              
# printing original list
print("The original list is : " + str(test_list))
 
# initializing search set
search_set = {6, 2, 8}
 
# repeat repeats all the occurrences of elements using operator.countOf()
res = list(chain.from_iterable((repeat(ele, op.countOf(test_list,ele))
                                for ele in search_set)))
 
# printing result
print("Set present list elements : " + str(res))


Output

The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [8, 2, 2, 6, 6]

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #5:Using itertools.filterfalse() function

Python3




# Python3 code to demonstrate working of
# Elements from list in set
 
import itertools
 
# initializing list
test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]
             
# printing original list
print("The original list is : " + str(test_list))
 
# initializing search set
search_set = {6, 2, 8}
 
# repeat repeats all the occurrences of elements
res = list(itertools.filterfalse(lambda x: x not in search_set,test_list))
 
# printing result
print("Set present list elements : " + str(res))


Output

The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [6, 2, 2, 6, 8]

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #6: using list comprehension

Python3




# initializing list
test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing search set
search_set = {6, 2, 8}
 
# finding elements from list in set using list comprehension
res = [ele for ele in test_list if ele in search_set]
 
# printing result
print("Set present list elements : " + str(res))
#THIS CODE IS CONTRIBUTED BY VIANY PINJALA.


Output

The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [6, 2, 2, 6, 8]

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #7: using numpy

Python3




import numpy
import numpy as np
 
# initializing list
test_list = numpy.array([5, 6, 2, 3, 2, 6, 5, 8, 9])
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing search set
search_set = list({6, 2, 8})
 
# finding elements from list in set using numpy
res = np.in1d(test_list, search_set)
 
# printing result
print("Set present list elements : " + str(test_list[np.where(res)]))


Output:

The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [6, 2, 2, 6, 8]

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #8: Using set operations with functools.reduce and lambda function:

Step-by-step approach:

  • Initialize the test_list with the given list of integers.
  • Create a set search_set with the given set of integers to search for.
  • Use the reduce() function from the functools module to loop through each element b of test_list.
  • For each element b of test_list, check if it is in the search_set using the if statement inside the lambda function.
  • If b is in search_set, append it to the result list a by returning a + [b] from the lambda function.
  • If b is not in search_set, do not append it to the result list a and simply return a.
  • After looping through all elements of test_list, reduce() returns the final value of a, which is the list of elements in test_list that are also in search_set.
  • Print the resulting list of elements that are in both test_list and search_set.

Below is the implementation of the above approach:

Python3




import functools
# initializing list
test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]
# printing original list
print("The original list is : " + str(test_list))
# initializing search set
search_set = {6, 2, 8}
result = functools.reduce(lambda a, b: a + [b] if b in search_set else a, test_list, [])
# printing result
print("Set present list elements : " + str(result))
#This code is contributed by Rayudu.


Output

The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [6, 2, 2, 6, 8]

Time complexity : O(n), where n is the length of the test_list. This is because the reduce() function loops through each element of test_list exactly once, and the if statement inside the lambda function has constant time complexity.
Auxiliary space: O(n), where n is the length of the test_list. This is because the resulting list result could potentially contain all elements of the test_list (in the case where all elements are in the search set), so the space required for result is proportional to the size of test_list.

Method #9: Using heapq:

  1. Initialize the test_list with some integers.
  2. Print the original list.
  3. Create an empty list named ‘result’.
  4. Initialize the search_set with some integers.
  5. Initialize freq_set by counting the elements of the search_set.
  6. Loop through each element ‘i’ in the test_list.
  7. Check if the element ‘i’ is present in freq_set.
  8. If it is present, append ‘i’ to the ‘result’ list.
  9. Print the list of elements present in the set.

Python3




from collections import Counter
import heapq
 
# initializing list
test_list = [5, 6, 2, 3, 2, 6, 5, 8, 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing search set
search_set = {6, 2, 8}
freq_set = Counter(search_set)
 
# use heapq to create a priority queue of elements to be included in the result
heap = []
for i in test_list:
  if i in freq_set.keys():
      heapq.heappush(heap, i)
 
# pop elements from the priority queue and add them to the result list
result = []
while heap:
    result.append(heapq.heappop(heap))
 
# printing result
print("Set present list elements : " + str(result))
 
#This code is contributed by Jyothi pinjala


Output

The original list is : [5, 6, 2, 3, 2, 6, 5, 8, 9]
Set present list elements : [2, 2, 6, 6, 8]

The time complexity :O(n log n), where n is the length of the input list test_list. The Counter() function has a time complexity of O(n), the heapq.heappush() function has a time complexity of O(log n) when inserting an element, and the heapq.heappop() function has a time complexity of O(log n) when removing an element. Since we are iterating over the input list once and performing these operations on each element, the overall time complexity is O(n log n).

The auxiliary space : O(n), where n is the length of the input list test_list. We are creating a heap list with at most n elements, and a result list with at most n elements. Additionally, we are creating a freq_set dictionary to store the frequency of elements in the search_set set, which has a space complexity of O(k), where k is the size of the search_set set. Since k is a constant in this case, we can simplify the space complexity to O(n).



Last Updated : 03 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads