When you have a long list and want to create permutations that match the length of a shorter list, you're essentially creating partial permutations or k-permutations.
The Problem
Given:
- Long list:
[A, B, C, D, E]
(5 items) - Short list:
[X, Y]
(2 items)
You want permutations of the long list with length 2.
Python Solutions
1: Using itertools.permutations()
from itertools import permutations
long_list = ['A', 'B', 'C', 'D', 'E']
short_list = ['X', 'Y']
result = list(permutations(long_list, len(short_list)))
print(result[:5]) # First 5 results
Output:
[('A', 'B'), ('A', 'C'), ('A', 'D'), ('A', 'E'), ('B', 'A')]
2: Manual approach with nested loops
long_list = ['red', 'blue', 'green', 'yellow']
short_list = ['item1', 'item2', 'item3']
result = []
for i in range(len(long_list)):
for j in range(len(long_list)):
for k in range(len(long_list)):
if i != j != k != i: # Ensure no duplicates
result.append((long_list[i], long_list[j], long_list[k]))
if len(result) >= 10: # Limit for demo
break
if len(result) >= 10:
break
if len(result) >= 10:
break
print(result)
[('red', 'blue', 'green'), ('red', 'blue', 'yellow'), ('red', 'green', 'blue'), ('red', 'green', 'yellow'), ('red', 'yellow', 'blue'), ('red', 'yellow', 'green'), ('blue', 'red', 'green'), ('blue', 'red', 'yellow'), ('blue', 'green', 'red'), ('blue', 'green', 'yellow')]
Real-World Examples
1: Team Selection
from itertools import permutations
players = ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve']
positions = ['Captain', 'Vice-Captain'] # 2 positions to fill
team_combinations = list(permutations(players, len(positions)))
print(f"Possible leadership teams: {len(team_combinations)}")
Output is 20 combinations (5×4):
[('Alice', 'Bob'),
('Alice', 'Charlie'),
('Alice', 'Diana'),
('Alice', 'Eve'),
('Bob', 'Alice'),
('Bob', 'Charlie'),
2: Color Combinations
colors = ['red', 'blue', 'green', 'yellow', 'purple']
design_slots = ['primary', 'secondary', 'accent'] # 3 slots
color_schemes = list(permutations(colors, len(design_slots)))
print(f"Total color schemes: {len(color_schemes)}")
Output: 60 combinations (5×4×3)
[('red', 'blue', 'green'),
('red', 'blue', 'yellow'),
('red', 'blue', 'purple'),
('red', 'green', 'blue'),
('red', 'green', 'yellow'),
('red', 'green', 'purple'),
('red', 'yellow', 'blue'),
Key Points
- Formula: For n items choosing k positions = n!/(n-k)!
- Order matters: (A,B) ≠ (B,A)
- No repetition: Each item used only once per permutation
- Memory warning: Large lists create many combinations quickly
Quick Reference
# Get k-length permutations from n-length list
from itertools import permutations
result = list(permutations(long_list, len(short_list)))
This approach works for any scenario where you need ordered selections from a larger set matching a target length.