When working with lists in Python, you might need to match all possible permutations of a longer list against a shorter list. This is useful in scenarios like:
- Generating possible sequences of a fixed length from a larger pool of items
- Finding all ordered combinations of a subset from a larger list
- Testing different arrangements in optimization or search problems
Example 1: Using itertools.permutations
The easiest way is to use itertools.permutations
, which generates all possible ordered arrangements of a given length.
from itertools import permutations
long_list = ['A', 'B', 'C', 'D']
short_length = 2 # We want permutations of length 2
# Generate all possible permutations of length 2
perms = permutations(long_list, short_length)
for perm in perms:
print(perm)
Output:
('A', 'B')
('A', 'C')
('A', 'D')
('B', 'A')
('B', 'C')
... (and so on)
Example 2: Matching Permutations Against a Target List
If you want to check which permutations match a specific short list:
from itertools import permutations
long_list = ['A', 'B', 'C', 'D']
target = ['B', 'A'] # We want to find if this permutation exists
perms = permutations(long_list, len(target))
if tuple(target) in perms:
print("Match found!")
else:
print("No match.")
Output: Match found!
Example 3: Storing Permutations in a List
If you need all permutations stored in a list for further processing:
from itertools import permutations
long_list = ['A', 'B', 'C']
short_length = 2
all_perms = list(permutations(long_list, short_length))
print(all_perms)
Output:
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
Example 4: Permutations with Repeated Elements (Using product
)
If you want to allow repeated elements (like ('A', 'A')
), use itertools.product
instead:
from itertools import product
long_list = ['A', 'B', 'C']
short_length = 2
perms_with_repeats = list(product(long_list, repeat=short_length))
print(perms_with_repeats)
Output:
[('A', 'A'), ('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'B'), ('C', 'C')]
Key Takeaways
permutations()
→ Ordered, non-repeating sequences.product()
→ Ordered, allows repeating elements.- Convert permutations to a list if you need to reuse them.
- Use
tuple(target)
to check if a specific permutation exists.
This approach is efficient and leverages Python’s built-in libraries for clean and fast results.