![]() |
VOOZH | about |
The permutations() function in Python, part of the itertools module, generates all possible ordered arrangements of a given iterable (like a list, string, or tuple). Unlike combinations, where order doesn't matter, permutations consider the order of elements. It returns an iterator producing tuples, each representing a unique permutation of the input elements. Example:
Output
('G', 'e', 'E', 'K')
('G', 'e', 'K', 'E')
('G', 'E', 'e', 'K')
('G', 'E', 'K', 'e')
('G', 'K', 'e', 'E')
('G', 'K', 'E', 'e')
('e', 'G', 'E', 'K')
('e', 'G', 'K', 'E')
('e', 'E', 'G', 'K')
('e', 'E', 'K', 'G')
('e', 'K', 'G', 'E')
('e', 'K', 'E', 'G')
('E', 'G', 'e', 'K')
('E', 'G', 'K', 'e')
('E', 'e', 'G', 'K')
('E', 'e', 'K', 'G')
('E', 'K', 'G', 'e')
('E', 'K', 'e', 'G')
('K', 'G', 'e', 'E')
('K', 'G', 'E', 'e')
('K', 'e', 'G', 'E')
('K', 'e', 'E', 'G')
('K', 'E', 'G', 'e')
('K', 'E', 'e', 'G')
Explanation:itertools.permutations() generate all ordered arrangements of the string "GeEK". It iterates over the resulting iterator and prints each permutation as a tuple. The default length of permutations is the full length of the string.
itertools.permutations(iterable, r)
Parameters:
Returns: An iterator that produces tuples, each representing a unique permutation of the elements from the iterable. If r is specified, it generates permutations of length r.
Example 1: Permutations with mixed data types
[(1, 'geeks'), ('geeks', 1)]
[(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
Explanation: In the first case, it generates pairs from the list [1, 'geeks'], considering each element's position. In the second case, it generates pairs from the range [0, 1, 2], producing all possible ordered combinations of two elements. The length of each permutation is defined by the second argument (2).
Example 2: Permutations with repeated elements
[(1, 1, 2), (1, 2, 1), (1, 1, 2), (1, 2, 1), (2, 1, 1), (2, 1, 1)]
Explanation: Even though there are duplicate elements in the input list, permutations() treats them as unique by position. So it generates all possible ordered arrangements, even if they look the same. Use set() to get only unique permutations.
Example 3: Permutations of a string with specified length
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
Explanation: This code generates all possible ordered arrangements of length 3 from the string "ABC". Since the string has three unique characters, the function will generate all permutations of length 3.