Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python itertools.permutations() Function



The Pythonitertools.permutations() function is used to generate all possible ordered arrangements (permutations) of elements from a given iterable. It allows you to specify the length of each permutation.

This function is useful in combinatorial problems where order matters, such as password generation, game mechanics, and arrangement problems.

Syntax

Following is the syntax of the Python itertools.permutations() function −

itertools.permutations(iterable, r=None)

Parameters

This function accepts the following parameters −

  • iterable: The input iterable whose elements will be arranged in different orders.
  • r (optional): The length of each permutation. If not specified, it defaults to the length of the iterable.

Return Value

This function returns an iterator that produces tuples representing all possible permutations.

Example 1

Following is an example of the Python itertools.permutations() function. Here, we generate all possible orderings of a list of numbers −

import itertoolsnumbers = [1, 2, 3]result = itertools.permutations(numbers)for item in result:   print(item)

Following is the output of the above code −

(1, 2, 3)(1, 3, 2)(2, 1, 3)(2, 3, 1)(3, 1, 2)(3, 2, 1)

Example 2

Here, we specify a permutation length of 2, generating pairs of elements from the given set −

import itertoolsletters = ['A', 'B', 'C']result = itertools.permutations(letters, 2)for item in result:   print(item)

Output of the above code is as follows −

('A', 'B')('A', 'C')('B', 'A')('B', 'C')('C', 'A')('C', 'B')

Example 3

Now, we use itertools.permutations() function to generate all possible orders of characters in a string −

import itertoolsword = "DOG"result = itertools.permutations(word)for item in result:   print(''.join(item))

The result obtained is as shown below −

DOGDGOODGOGDGDOGOD

Example 4

When working with passwords or combination locks, the itertools.permutations() function can help generate all possible sequences −

import itertoolsdigits = ['1', '2', '3']result = itertools.permutations(digits, 3)for combination in result:   print(''.join(combination))

The result produced is as follows −

123132213231312321
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp