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 find all the Combinations in a list with the given condition
When you need to find combinations in a list with a specific condition, you can use iteration, the yield operator, and list comprehension. This approach is useful for merging two lists by taking K elements from each list alternately.
Syntax
The basic approach involves creating a generator function that yields elements based on a given condition ?
def merge_function(list1, list2, k):
# Generator function logic
yield element
Example
Below is a demonstration that merges two lists by alternating K elements from each ?
def merge_the_vals(my_list_1, my_list_2, K):
index_1 = 0
index_2 = 0
while index_1 < len(my_list_1) and index_2 < len(my_list_2):
# Take K elements from first list
for i in range(K):
if index_1 < len(my_list_1):
yield my_list_1[index_1]
index_1 += 1
# Take K elements from second list
for i in range(K):
if index_2 < len(my_list_2):
yield my_list_2[index_2]
index_2 += 1
# Define the lists
my_list_1 = [12, 56, 14, 28, 61, 73, 59, 90]
my_list_2 = [52, 16, 17, 34, 43, 16, 84, 57]
print("The first list is:")
print(my_list_1)
print("The second list is:")
print(my_list_2)
K = 2
print("The value of K is:")
print(K)
# Generate combinations using list comprehension
my_result = [element for element in merge_the_vals(my_list_1, my_list_2, K)]
print("The resultant list is:")
print(my_result)
print("The list after sorting is:")
my_result.sort()
print(my_result)
The first list is: [12, 56, 14, 28, 61, 73, 59, 90] The second list is: [52, 16, 17, 34, 43, 16, 84, 57] The value of K is: 2 The resultant list is: [12, 56, 52, 16, 14, 28, 17, 34, 61, 73, 43, 16, 59, 90, 84, 57] The list after sorting is: [12, 14, 16, 16, 17, 28, 34, 43, 52, 56, 57, 59, 61, 73, 84, 90]
How It Works
The function uses two index variables to track positions in both lists. It alternately yields K elements from each list until all elements are processed. The yield keyword creates a generator that produces values on demand.
Key Points
The generator function takes two lists and a value K as parameters
It uses
yieldto return elements one by one without storing them in memoryIndex bounds checking prevents errors when lists have different lengths
List comprehension collects all yielded values into a final list
The result can be sorted using the
sort()method
Conclusion
This approach efficiently combines two lists by alternating K elements from each. The generator function with yield provides memory-efficient processing, making it suitable for large datasets.
