Find Number Combinations in Python

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Nested Loops

What You’ll Learn

This page covers two classic nested-loop patterns: listing all orderings of three numbers (permutations), and listing unordered pairs or triples (combinations). You will see distinct-index checks, the j = i + 1 trick, a live preview, worked Python examples, edge cases, and complexity.

Permutations

Order matters

All 3! = 6 orderings of three values.

Combinations

Order ignored

Unordered pairs with j > i.

Distinct i,j,k

No reuse

Do not reuse the same index in one line.

n Choose r

C(n,2)

Pair loops list each 2-subset once.

Live Preview

1, 2, 3

List all orderings for three integers.

O(n²) Pairs

Nested cost

Pairs are quadratic; triples are cubic.

Introduction

Number combinations on this page means listing selections from a small list with nested loops. When order matters, you print permutations. When order does not matter, you print combinations.

Interviews love these patterns because they force you to talk about indices, duplicates, and asymptotic growth. Nested loops are enough for small sample sizes; larger inputs often use dedicated libraries later.

Why it matters?

It is the clearest way to practice nested loops while learning the difference between order-sensitive and order-free listing.

Key Highlights

Permutations

Distinct i, j, k indices.

Pairs

Use j = i + 1.

Triples

Use i < j < k.

Count

3! = 6; C(4,2) = 6.

In short: nested loops pick indices; enforce distinct indices for permutations and increasing indices for combinations.

📝 Problem & Approach

Given a small list of numbers, print either all orderings of three values or all unordered selections of size 2 (or 3).

python
# [1, 2, 3] -> 6 orderings (permutations)
# [10, 20, 30, 40] -> 6 unordered pairs

Inputs & Outputs

ItemTypeDescription
arrlist[int]Source numbers to rearrange or pair.
Permutationstext linesOne line per ordering of three values.
Combinationstext linesOne line per unordered pair or triple.

Minimal workflow

Pseudocode
// Permutations of 3
for i in 0..2:
  for j in 0..2:
    for k in 0..2:
      if i, j, k are all distinct:
        print arr[i], arr[j], arr[k]

// Unordered pairs
for i in 0..n-2:
  for j in i+1..n-1:
    print arr[i], arr[j]

Method comparison

PatternOrder?Index rule
Permutations of 3Mattersi != j != k (all distinct)
Unordered pairsIgnoredj = i + 1 .. n-1
Unordered triplesIgnoredi < j < k

⚡ Quick Reference

GoalPattern
Distinct indicesif i != j and j != k and i != k:
Unordered pairsfor j in range(i + 1, n):
Unordered triplesfor k in range(j + 1, n):
Count perms of 33! = 6
Count pairsC(n, 2) = n*(n-1)/2
Library lateritertools.permutations / combinations

📋 Permutation vs Combination vs Library

Same nested-loop toolbox — different index rules and interview signals.

Permutations
distinct i,j,k

Order matters — 6 lines for [1,2,3]

Combinations
j = i + 1

Order ignored — no reverse duplicates

itertools
combinations(...)

Production shortcut after you can explain loops

Interview tip
say order rule

State whether order matters up front

Context

When This Problem Shows Up

Reach for nested selection loops whenever you need every ordering or every unordered subset.

  1. Nested-loop drills

    Practice indices and distinctness checks.

  2. Perm vs combo talk

    Clarify whether order changes the answer.

  3. Brute-force warm-ups

    Try all pairs before smarter algorithms.

  4. Counting practice

    Connect output line count to n! and C(n,r).

  5. Not for huge n

    Deep nested loops explode quickly.

Key benefit: one page that teaches both order-sensitive and order-free listing with the same nested-loop skill.

🔮 Live Preview

Enter three integers (e.g. 1, 2, 3) and list all orderings.

Use commas or spaces. Duplicate values may cause repeated-looking lines.

Live result
Press “List orderings”.

Examples Gallery

Three complete Python programs — permutations of three numbers, unordered pairs, and unordered triples. Click View Output to reveal sample console results.

📚 Getting Started

Order matters: list every arrangement of three values.

Example 1 — All Orderings of Three Numbers

Order matters here, so this is permutation listing.

python
def print_three_permutations(arr: list[int]) -> None:
    print("All orderings (permutations) of the three numbers:")
    for i in range(3):
        for j in range(3):
            for k in range(3):
                if i != j and j != k and i != k:
                    print(arr[i], arr[j], arr[k])


def main() -> None:
    arr = [1, 2, 3]
    print_three_permutations(arr)


if __name__ == "__main__":
    main()

How It Works

Each loop picks one position. The distinct-index guard ensures one slot is not reused in the same line. For three distinct values you always get 3! = 6 lines.

⚡ Combinations (Order Ignored)

Increasing indices keep each unordered selection once.

Example 2 — All Pairs from Four Numbers

Order does not matter in this pair listing, so we use j = i + 1.

python
def print_unordered_pairs(arr: list[int]) -> None:
    n = len(arr)
    print(f"All unordered pairs (choose 2 from {n}):")
    for i in range(n):
        for j in range(i + 1, n):
            print(arr[i], arr[j])


def main() -> None:
    arr = [10, 20, 30, 40]
    print_unordered_pairs(arr)


if __name__ == "__main__":
    main()

How It Works

Starting the inner loop at i + 1 skips reverse duplicates like (20, 10). That is choose 2 from 4, so you get C(4, 2) = 6 pairs.

Example 3 — Unordered Triples (Choose 3)

Extend the pair idea to three nested loops with i < j < k.

python
def print_unordered_triples(arr: list[int]) -> None:
    n = len(arr)
    print(f"All unordered triples (choose 3 from {n}):")
    for i in range(n):
        for j in range(i + 1, n):
            for k in range(j + 1, n):
                print(arr[i], arr[j], arr[k])


def main() -> None:
    arr = [10, 20, 30, 40]
    print_unordered_triples(arr)


if __name__ == "__main__":
    main()

How It Works

Each triple appears once because indices always increase. C(4, 3) = 4 lines — the natural extension of Example 2.

🧠 How Nested Selection Works

1

Store values

Put numbers in a list for index access.

Setup
2

Nest the loops

Each loop picks one index / position.

Loops
3

Apply the index rule

Distinct indices, or strictly increasing indices.

Filter
=

Print each selection

One line per valid tuple or pair.

🔎 Worked Walkthrough — [1, 2, 3]

Trace how distinct indices produce the six permutations.

i, j, kValuesPrinted?
0,1,21 2 3Yes
0,2,11 3 2Yes
0,0,1No (i == j)
1,0,22 1 3Yes
remaining valid triplesTotal 6 lines

Invalid index triples are skipped; only distinct i, j, k print.

Use Cases

Where listing combinations and permutations shows up beyond the interview prompt.

1. Nested Loop Practice

Learn indices and guards clearly.

Example: three nested fors.

2. Brute-Force Pairs

Try every unordered pair first.

Example: Example 2 style.

3. Counting Checks

Verify line count equals n! or C(n,r).

Example: 6 perms, 6 pairs.

4. Teaching Order

Show why (10,20) != (20,10) in perms.

Example: perm vs combo.

5. Bridge to Factorial

Permutation counts connect to n!.

Example: related topic.

6. Small Grids Only

Keep n small for hand-written loops.

Example: n ≈ 3–10.

Pro Tip: open with “Does order matter?” — that single question picks the right index rule.

Advantages

Why nested-loop listing works well for small interview problems.

  1. 1. Easy to Trace

    Dry-run indices on paper and see each line.

  2. 2. Teaches Both Ideas

    Same loops, two meaning of order.

  3. 3. No Extra Libraries

    Works with plain Python loops.

  4. 4. Extensible

    Pairs become triples by adding one loop.

Pro Tip: lead with loops in interviews; mention itertools only as a production aside.

Usage Tips

Small habits that keep combination/permutation code interview-ready.

  1. 1. Ask About Order

    Decide permutation vs combination first.

  2. 2. Prefer Increasing Indices

    For combinations, j = i + 1 beats filtering later.

  3. 3. Count Expected Lines

    Check against n! or C(n,r) before finishing.

  4. 4. Watch Duplicate Values

    Distinct indices ≠ unique printed value tuples.

  5. 5. Keep n Small

    Mention itertools for large production lists.

Pro Tip: if you see both (a,b) and (b,a), you probably wanted combinations, not permutations.

Common Pitfalls

Mistakes that commonly break combination and permutation listings.

  1. 1. Reusing an Index

    Printing arr[i] twice in one line.

    → Require all indices distinct for perms.

  2. 2. Reverse Pair Duplicates

    Printing both (10,20) and (20,10).

    → Start inner loop at i + 1.

  3. 3. Confusing Terms

    Calling permutations “combinations”.

    → State whether order matters.

  4. 4. Ignoring Duplicate Values

    Expecting unique lines when input repeats.

    → Filter by value if needed.

  5. 5. Huge Nested Depth

    Hand-writing O(n^k) for large n and k.

    → Use better algorithms or libraries.

Edge Cases

Handle these before claiming the listing is complete.

Duplicates

Repeated values

Distinct indices can still print identical-looking triples.

Small n

Too few elements

For pair listing, if n < 2 there are no pairs to print.

n = 3

Exact size for perms

Example 1 assumes exactly three elements.

Triples

n < 3

Unordered triples print nothing.

Large

Large n

Output volume grows fast — O(n²) / O(n³).

Empty

Empty list

No selections — print a clear message if needed.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Order rule. Permutations count arrangements; combinations count subsets.
  • Counts. P(3,3) = 6; C(4,2) = 6; C(4,3) = 4.
  • Linked to factorial. Full permutations of n distinct items equal n!.
  • Index vs value. Distinct indices do not guarantee distinct printed values when the list has duplicates.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Reproduce 6 perms

  • Run Example 1 on [1,2,3]
  • Confirm exactly 6 lines

2. Pairs from 4

  • Reproduce Example 2
  • Confirm C(4,2) = 6

3. Triples from 4

  • Implement Example 3
  • Confirm C(4,3) = 4

4. Duplicate values

  • Try [1,1,2] in the live preview
  • Notice repeated-looking lines

Notes

  • Permutations: distinct i, j, k indices give all orderings.
  • Combinations: j > i avoids duplicate pair reversals.
  • Concept: order matters for permutations, not for combinations.
  • For many elements, prefer dedicated algorithms or modules. Repeated values may create repeated-looking lines; filter if unique output is required.

Quick Takeaway: nest loops, then choose distinct indices (perms) or increasing indices (combos).

⏱️ Time and Space Complexity

ProgramTimeExtra space
Triple nested loops (fixed size 3)O(1) for fixed inputO(1)
Pairs from n elementsO(n²)O(1)
Triples from n elementsO(n³)O(1)

Cost grows with how many selections you enumerate; output size is part of the story.

Wrap Up

🎉 Conclusion

Number combinations on this page are nested-loop listings: distinct indices for permutations, increasing indices for combinations. Count expected lines with n! or C(n,r), watch duplicate values, and keep n small for hand-written loops.

Practice the three examples above, then continue to checking odd numbers.

Ask “does order matter?” then pick distinct indices or j = i + 1.

💡 Best Practices

✅ Do

  • State whether order matters
  • Use distinct indices for perms
  • Use j = i + 1 for pairs
  • Check line count vs formula
  • Keep sample n small

❌ Don’t

  • Reuse the same index in one line
  • Print reverse pair duplicates
  • Mix up perm vs combo vocabulary
  • Ignore duplicate input values
  • Deep-nest huge n without a plan

Key Takeaways

Knowledge Unlocked

Five things to remember about number combinations

List selections with nested loops the interview-friendly way.

5
Core concepts
C 02

Combos

j = i + 1

Rule
! 03

Distinct

No reused index

Guard
# 04

Count

n! / C(n,r)

Check
O 05

Cost

O(n²) pairs

Analysis

❓ Frequently Asked Questions

This page shows two patterns: all orderings of three numbers (permutations), and all unordered pairs from four numbers (combinations).
Each loop picks one position in the triple. Distinct index checks ensure one array slot is not reused in the same line.
There are 3! = 6 permutations.
It avoids duplicates like both (10,20) and (20,10). Each unordered pair appears once.
Yes. Example 2 is choose 2 from 4. Loops list each subset explicitly.
Pair generation is O(n^2). Triple nested loops over n elements are O(n^3).
In real apps, itertools.permutations and combinations are fine. Interviews often want you to show nested loops first.
Distinct indices can still print identical-looking lines. Filter by value if you need unique printed tuples.
Use i < j < k (three nested loops) so each subset of size 3 appears once.

Did you Know? 🔊

In math, a combination ignores order, while a permutation treats different orders as different results. This page demonstrates both patterns using simple nested loops.

Continue to Odd Number

Learn how to check whether a number is odd in Python.

Odd number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful