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 – Cross Pattern Pairs in List
When it is required to display cross pattern pairs in list, a list comprehension and the multiplication operator are used to create all possible products between elements of two lists.
What is Cross Pattern Pairs?
Cross pattern pairs refer to multiplying each element from the first list with every element from the second list, creating a Cartesian product of multiplications.
Example
my_list_1 = [14, 35, 26]
my_list_2 = [36, 24, 12]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
result = [i * j for j in my_list_1 for i in my_list_2]
print("The result is :")
print(result)
Output
The first list is : [14, 35, 26] The second list is : [36, 24, 12] The result is : [504, 336, 168, 1260, 840, 420, 936, 624, 312]
How It Works
The list comprehension [i * j for j in my_list_1 for i in my_list_2] works as follows:
For each element
jinmy_list_1(14, 35, 26)Multiply it with each element
iinmy_list_2(36, 24, 12)The pattern creates: 14×36, 14×24, 14×12, then 35×36, 35×24, 35×12, then 26×36, 26×24, 26×12
Alternative Method Using Nested Loops
my_list_1 = [14, 35, 26]
my_list_2 = [36, 24, 12]
result = []
for j in my_list_1:
for i in my_list_2:
result.append(i * j)
print("Cross pattern result:")
print(result)
Cross pattern result: [504, 336, 168, 1260, 840, 420, 936, 624, 312]
Conclusion
Cross pattern pairs multiply each element from one list with every element from another list. List comprehension provides a concise way to achieve this Cartesian product multiplication.
