How to Get All Combinations of a List in Python

Generate and display all combinations of a given length from a list using Python's itertools.combinations.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

16 lines
Python 3.9+
from itertools import combinations

def list_combinations(items, r):
    """Return all combinations of length r from a list."""
    return list(combinations(items, r))

if __name__ == "__main__":
    fruits = ["apple", "banana", "cherry", "date"]
    pick = 2
    result = list_combinations(fruits, pick)
    
    print(f"List: {fruits}")
    print(f"Choosing {pick} at a time:")
    for combo in result:
        print(combo)
    print(f"Total combinations: {len(result)}")

Output

stdout
List: ['apple', 'banana', 'cherry', 'date']
Choosing 2 at a time:
('apple', 'banana')
('apple', 'cherry')
('apple', 'date')
('banana', 'cherry')
('banana', 'date')
('cherry', 'date')
Total combinations: 6

How it works

itertools.combinations yields tuples of the requested length without repeating elements and without regard to order. The function wraps the iterator in list() so you can inspect or reuse the results directly. Because combinations are emitted in lexicographic order based on the input, output is deterministic and easy to reason about. This is a standard-library solution, so no third-party imports are needed, making it efficient and dependency-free for production code.

Common mistakes

  • Confusing combinations with permutations — combinations ignore order, permutations do not.
  • Passing r larger than the list length, which returns an empty list instead of an error.
  • Forgetting to convert the iterator to a list when you need to index or slice the results.

Variations

  1. Use `itertools.permutations` if you need ordered selections (arrangements).
  2. Use `itertools.combinations_with_replacement` to allow the same item to appear multiple times.

Real-world use cases

  • Generating all possible team pairings for a scheduling or tournament application.
  • Creating feature combinations for A/B testing configurations in an experimentation platform.
  • Enumerating subset combinations during a brute-force search in an algorithmic trading backtester.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.