

In this tutorial of Python Examples, we learned how to use list comprehension for two lists to generate a new list. In the following example, we shall take two lists, and generate permutations of items in these two lists. = Example 2: Permutations of items in Two Lists using Comprehension In the following example, we shall take two lists, and generate a new list using list comprehension. So, the list comprehension with two lists generates a list with number of elements equal to the product of lengths of the two lists.Įxample 1: List Comprehension using Two Lists The above list comprehension is equivalent to the following code using nested for loops. In the following example, we shall take two lists, and generate permutations of items in these two lists. The permutations() function takes a sequence (here a list of three integers) and a number, which is the number of items you want in each smaller group. The first for loop iterates for each element in list_1, and the second for loop iterates for each element in list_2. Where expression can contain variables x and y. Syntaxįollowing is the syntax of List Comprehension with two lists. In this tutorial, we will learn how to use List Comprehension with Two Lists and create a new list.

List Comprehension is more idiomatic and concise when compared to looping statements, in creating lists. Python List Comprehension is a way of creating Python Lists. Example 2: Permutations of items in Two Lists using Comprehension.It is the shortest technique to find the permutation. The NumPy Random module provides two methods for this: shuffle () and permutation (). 3, 2, 1 is a permutation of 1, 2, 3 and vice-versa. Example 1: List Comprehension using Two Lists Method 3 (Direct Function) We can do it by simply using the built-in permutation function in itertools library. A permutation refers to an arrangement of elements.
