Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Python’s standard library to generate or count selections: itertools.permutations() is for ordered selections without replacement, and itertools.combinations() is for unordered selections without replacement. If items may repeat, use itertools.product() or itertools.combinations_with_replacement(), depending on whether order matters. If you only need the number of outcomes, use math.perm() or math.comb() instead of generating them.

Permutations vs. combinations: does order matter?

A permutation is an ordered selection. From A, B, and C, selecting two gives AB, AC, BA, BC, CA, and CB. AB and BA are different outcomes.

A combination is an unordered selection. Choosing two of the same three items gives AB, AC, and BC; reversing a pair does not create a new selection.

Think of race positions as a permutation because first and second place differ. Choosing members for a committee is a combination because the order of the chosen members does not matter. Order is only part of the decision, though: you must also decide whether an item can be selected more than once.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Choose the right Python function

What you need Python tool Order matters? Can an input position repeat?
Generate ordered selections of length r itertools.permutations() Yes No
Generate unordered selections of length r itertools.combinations() No No
Generate unordered selections with repetition itertools.combinations_with_replacement() No Yes
Generate ordered sequences with repetition itertools.product() Yes Yes
Count ordered selections without replacement math.perm() Yes No
Count unordered selections without replacement math.comb() No No
Get one random selection without replacement random.sample() Returned order is meaningful No
Randomly rearrange an entire list random.shuffle() Yes No

For example, a PIN where digits can repeat is an ordered sequence with repetition, so product() fits. If digits cannot repeat, use permutations. For topping quantities where order does not matter and a topping can be chosen more than once, use combinations with replacement.

Generate permutations with itertools.permutations()

Import permutations from itertools. Its optional r argument sets the selection length; if omitted, Python generates full-length permutations.

from itertools import permutations

items = ["A", "B", "C"]

for result in permutations(items, 2):
    print(result)

Output:

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

Each result is a tuple. The function returns an iterator, so results can be handled one at a time rather than stored together. Its count for n input positions and selection length r is n! / (n - r)!. For three inputs and two positions, that is 3 × 2 = 6.

Generate combinations with itertools.combinations()

Use combinations(iterable, r) when selecting r items without replacement and the order of selection does not matter.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from itertools import combinations

items = ["A", "B", "C"]

for result in combinations(items, 2):
    print(result)

Output:

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

The pair ('B', 'A') is not emitted separately: it represents the same combination as ('A', 'B'). The count is n! / (r! × (n - r)!); for three inputs taken two at a time, it is three.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Both functions accept iterables such as strings, lists, tuples, and ranges, and yield tuples. Their output follows the input order; they do not automatically sort values alphabetically. The official Python documentation for permutations() and documentation for combinations() describes these behaviors. The iterable is consumed into a tuple internally, so these functions are not appropriate for a genuinely unbounded input.

Count outcomes without generating them

When you need only a count, use the math module. math.perm(n, r) counts ordered selections without replacement, while math.comb(n, r) counts unordered selections without replacement.

from math import perm, comb

perm(10, 3)  # 720
comb(10, 3)  # 120

These functions were added in Python 3.8. They accept integer arguments and raise ValueError for negative arguments. If r is greater than n, both return 0. The corresponding iterators also yield no tuples when asked to select more positions than the input contains. For r = 0, each iterator yields one empty tuple, (): there is exactly one way to select nothing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For Python versions before 3.8, factorials can provide a compatibility fallback for valid nonnegative inputs with r ≤ n:

from math import factorial

def permutation_count(n, r):
    return factorial(n) // factorial(n - r)

def combination_count(n, r):
    return factorial(n) // (factorial(r) * factorial(n - r))

Counting first is a useful feasibility check. For example, perm(10, 10) is 3,628,800, while comb(50, 6) is 15,890,700. Those counts indicate why generating and storing every result can become impractical.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Allow repetition: products and combinations with replacement

Ordered sequences with repetition

Use product(iterable, repeat=r) when every position independently draws from the same pool and order matters. It is the Cartesian product of the pool with itself r times.

from itertools import product

list(product("AB", repeat=2))
# [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]

For n choices at each of r positions, there are n ** r sequences. Two positions and two symbols therefore produce 2 ** 2 = 4 outcomes. Unlike permutations, products allow a pool position to be used again.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Unordered selections with repetition

Use combinations_with_replacement(iterable, r) when order does not matter but a pool position may be selected more than once.

from itertools import combinations_with_replacement

list(combinations_with_replacement("ABC", 2))
# [('A', 'A'), ('A', 'B'), ('A', 'C'),
#  ('B', 'B'), ('B', 'C'), ('C', 'C')]

The number of outcomes for n input positions taken r at a time with replacement is comb(n + r - 1, r). For three choices taken two at a time, that is comb(4, 2) = 6. The official product() documentation and combinations_with_replacement() documentation provide further details.

Get a random selection instead of every possibility

If you need one random sample without replacement, random.sample() returns a list. Its returned order is a random ordered selection.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
import random

items = ["A", "B", "C", "D"]
ordered_sample = random.sample(items, k=3)

If the selection is conceptually a combination, normalize its display order so a pair appears consistently rather than sometimes as ('A', 'B') and sometimes as ('B', 'A'):

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
unordered_sample = tuple(sorted(random.sample(items, k=2)))

Use random.shuffle(items) to randomly reorder an entire list in place; it changes items. For a large integer population, a range can be sampled efficiently, for example random.sample(range(10_000_000), k=60). See the Python documentation for random.sample() and random.shuffle().

The standard random module uses the deterministic Mersenne Twister and is not suitable for cryptographic uses such as security-sensitive tokens or passwords. Use the secrets module for cryptographic randomness; gambling systems may also have specialized security and regulatory requirements beyond ordinary pseudorandom sampling.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle duplicate values deliberately

itertools treats input positions as distinct, even when their values are equal. Thus permutations("AAB", 2) generates six tuples, including two copies each of ('A', 'A'), ('A', 'B'), and ('B', 'A'). This is correct when the two A characters are distinct physical positions, but it can be surprising if the desired output is unique by value.

For a small result set, convert to a set to remove duplicate tuples after generation:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
from itertools import permutations

unique_results = set(permutations("AAB", 2))
# {('A', 'A'), ('A', 'B'), ('B', 'A')}

This still generates the duplicates first. For larger inputs, a frequency-aware generator can avoid producing duplicate-by-value permutations:

from collections import Counter

def unique_permutations(values, r=None):
    counts = Counter(values)
    r = len(values) if r is None else r

    def build(path):
        if len(path) == r:
            yield tuple(path)
            return

        for value in counts:
            if counts[value] == 0:
                continue

            counts[value] -= 1
            path.append(value)
            yield from build(path)
            path.pop()
            counts[value] += 1

    yield from build([])

list(unique_permutations("AAB", 2))
# [('A', 'A'), ('A', 'B'), ('B', 'A')]

For this implementation, the values must be usable as dictionary keys because Counter stores them as keys.

Process large result spaces without wasting memory

Iterate instead of materializing everything

A loop can process each result as it is produced:

from itertools import permutations

for result in permutations(items, 3):
    if result[0] == "A":
        print(result)

Avoid converting an iterator to a list unless you know the output is small enough to store. The iterator avoids holding all tuples at once, but it does not reduce the total work required if your program consumes every tuple. Full permutations grow as n!; length-r permutations grow as n! / (n - r)!; combinations grow as comb(n, r); products grow as n ** r; and combinations with replacement grow as comb(n + r - 1, r).

Take only a preview or first few results

Use itertools.islice() to stop after a fixed number of results without building the full list:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
from itertools import islice, permutations

first_five = islice(permutations(range(10), 3), 5)
for result in first_five:
    print(result)

Filter results or prune earlier

Filtering with a generator expression keeps the filtered results lazy:

from itertools import permutations

items = ["A", "B", "C", "D"]
valid = (
    result for result in permutations(items, 3)
    if result[0] != "D"
)

for result in valid:
    print(result)

This still constructs and checks every candidate permutation before deciding whether it passes the condition. When constraints make many partial candidates impossible, backtracking can prune those branches early. For example, this generator produces ordered selections without replacement and lets a condition be added before the recursion continues:

def arrangements(items, r):
    def build(path, remaining):
        if len(path) == r:
            yield tuple(path)
            return

        for index, item in enumerate(remaining):
            next_path = path + [item]
            next_remaining = remaining[:index] + remaining[index + 1:]

            # Add a constraint check here before descending.
            yield from build(next_path, next_remaining)

    yield from build([], list(items))

For ordinary unconstrained generation, prefer the concise built-in iterator. Custom backtracking is useful when it can reject an invalid partial path before exploring all of its possible extensions.

Common mistakes to avoid

  • Using permutations when order does not matter creates redundant outcomes; use combinations instead.
  • Using combinations for a code or sequence where position matters omits valid orderings; check whether repetition is allowed and use permutations or product accordingly.
  • Assuming permutations or combinations reuse an input position: neither does. Choose a replacement-enabled function if repetition is required.
  • Calling len(list(permutations(...))) just to count: use math.perm() or math.comb() for the relevant no-replacement count.
  • Assuming duplicate values are automatically collapsed: standard itertools functions distinguish input positions.
  • Assuming combinations sort input values: results follow the input sequence; sort the input first only if that is the intended output order.
  • Using random for passwords, tokens, or other security-sensitive randomness: use secrets.

Quick reference

Goal Example Meaning
Ordered selection, no replacement permutations("ABC", 2) Six ordered pairs
Unordered selection, no replacement combinations("ABC", 2) Three pairs
Ordered sequence, with repetition product("AB", repeat=2) Four sequences
Unordered selection, with repetition combinations_with_replacement("AB", 2) Three selections
Count ordered selections perm(10, 3) 720; Python 3.8+
Count unordered selections comb(10, 3) 120; Python 3.8+

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.