How to Generate a Collatz Sequence in Python

Generate the Collatz sequence for a given positive integer by repeatedly applying the 3n+1 rule until reaching 1.

Easy Python 3.8+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

17 lines
Python 3.8+
def collatz_sequence(n):
    if n <= 0:
        raise ValueError("n must be a positive integer")
    sequence = [n]
    while n != 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        sequence.append(n)
    return sequence

if __name__ == "__main__":
    start = 7
    result = collatz_sequence(start)
    print(f"Collatz sequence starting from {start}: {result}")
    print(f"Length: {len(result)}")

Output

stdout
Collatz sequence starting from 7: [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
Length: 17

How it works

The Collatz conjecture states that applying n // 2 for even numbers and 3 * n + 1 for odd numbers will always eventually reach 1 for any positive starting integer. The function accumulates each step in a list, starting with the initial value. An input validation guard ensures the function only accepts positive integers, raising a ValueError otherwise. The loop terminates when n becomes 1, so the sequence always includes the final 1.

Common mistakes

  • Forgetting to handle invalid input like zero or negative numbers, causing an infinite loop.
  • Using `/` instead of `//` for integer division, which produces floats and alters the sequence.
  • Not initializing the sequence list with the starting value, so the output omits the first term.

Variations

  1. Use a generator expression to yield values one at a time instead of building a full list.
  2. Wrap the function in a recursive implementation to generate the sequence recursively.

Real-world use cases

  • Implementing a teaching exercise in computer science courses to illustrate loops and conditionals.
  • Verifying the Collatz conjecture for ranges of numbers in computational number theory research.
  • Building a benchmark for performance testing of arithmetic-intensive loops in Python.

Sponsored

Run this sample

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

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.