I would recommend using a generator because

  • it allows you to generate sequences of arbitrary length without wasting memory
  • one might argue it is "pythonic".

In the following, I will use the Fibonacci sequence as an example because it takes a similar form to your problem.

def fibonacci(a=0, b=1, length=None):
    # Generate a finite or infinite sequence
    num = 0
    while length is None or num < length:
        # Evaluate the next Fibonacci number
        c = a + b
        yield c
        # Advance to the next item in the sequence
        a, b = c, a
        num += 1

Note that a corresponds to your x_n, b corresponds to x_{n-1}, and c corresponds to x_{n+1}. And a simple example:

>>> list(fibonacci(length=10))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

If you want to get the sequence into a numpy array

>>> np.fromiter(fibonacci(length=10), int)
array([ 1,  1,  2,  3,  5,  8, 13, 21, 34, 55])
Answer from Till Hoffmann on Stack Overflow
🌐
w3resource
w3resource.com › python-exercises › basic › python-basic-1-exercise-105.php
Python: Check whether a given sequence is linear, quadratic or cubic - w3resource
May 24, 2025 - Write a Python program to analyze a numerical sequence and classify it as linear, quadratic, or cubic using finite differences.
Top answer
1 of 2
1

I would recommend using a generator because

  • it allows you to generate sequences of arbitrary length without wasting memory
  • one might argue it is "pythonic".

In the following, I will use the Fibonacci sequence as an example because it takes a similar form to your problem.

def fibonacci(a=0, b=1, length=None):
    # Generate a finite or infinite sequence
    num = 0
    while length is None or num < length:
        # Evaluate the next Fibonacci number
        c = a + b
        yield c
        # Advance to the next item in the sequence
        a, b = c, a
        num += 1

Note that a corresponds to your x_n, b corresponds to x_{n-1}, and c corresponds to x_{n+1}. And a simple example:

>>> list(fibonacci(length=10))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

If you want to get the sequence into a numpy array

>>> np.fromiter(fibonacci(length=10), int)
array([ 1,  1,  2,  3,  5,  8, 13, 21, 34, 55])
2 of 2
1

I think you want the initial collection of terms. However, if it should happen that you, or anyone reading this question, might want individual terms then the sympy library comes in handy. Everything here up to the horizontal line is from Solve a recurrence relation.

>>> from sympy import *
>>> var('y')
y
>>> var('n', integer=True)
n
>>> f = Function('f')
>>> f = y(n)-2*y(n-1)-5*y(n-2)
>>> r = rsolve(f, y(n), [1, 4])

Once you have r you can either evaluate it for various values of n within the sympy facilities ...

>>> N(r.subs(n,1))
4.00000000000000
>>> N(r.subs(n,2))
13.0000000000000
>>> N(r.subs(n,10))
265333.000000000

Or you could 'lift' the code in r and re-use it for your own routines.

>>> r
(1/2 + sqrt(6)/4)*(1 + sqrt(6))**n + (-sqrt(6) + 1)**n*(-sqrt(6)/4 + 1/2)
🌐
Finxter
blog.finxter.com › home › learn python blog › how to create a sequence of linearly increasing values with numpy arange?
How to Create a Sequence of Linearly Increasing Values with Numpy Arange? - Be on the Right Side of Change
January 20, 2021 - The np.arange([start,] stop[, step]) function creates a new NumPy array with evenly-spaced integers between start (inclusive) and stop (exclusive). The step size defines the difference between subsequent values.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.linspace.html
numpy.linspace — NumPy v2.5 Manual
The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-create-a-sequence-of-linearly-increasing-values-with-numpy-arange
How to Create a Sequence of Linearly Increasing Values with Numpy Arrange? | GeeksforGeeks
August 16, 2022 - Python3 · #importing numpy module import numpy as np #create an elements from 34 to 50 with 4 step linearity print(np.arange(34,50,5)) Output: [34 39 44 49] Comment · More infoAdvertise with us · Next Article · How to get Almost Increasing Sequence of Integers in JavaScript?
🌐
SymPy
docs.sympy.org › latest › modules › series › sequences.html
Sequences - SymPy 1.14.0 documentation
If d is specified, find shortest linear recurrence of order \(\leq\) min(d, n/2) if possible. Returns list of coefficients [b(1), b(2), ...] corresponding to the recurrence relation x(n) = b(1)*x(n-1) + b(2)*x(n-2) + ... Returns [] if no recurrence is found. If gfvar is specified, also returns ordinary generating function as a function of gfvar. ... >>> from sympy import sequence, sqrt, oo, lucas >>> from sympy.abc import n, x, y >>> sequence(n**2).find_linear_recurrence(10, 2) [] >>> sequence(n**2).find_linear_recurrence(10) [3, -3, 1] >>> sequence(2**n).find_linear_recurrence(10) [2] >>> seq
Find elsewhere
🌐
Real Python
realpython.com › np-linspace-numpy
np.linspace(): Create Evenly or Non-Evenly Spaced Arrays – Real Python
July 3, 2026 - In the example above, you create a linear space with 25 values between -10 and 10. You use the num parameter as a positional argument, without explicitly mentioning its name in the function call. This is the form you’re likely to use most often. Let’s take a step back and look at what other tools you could use to create an evenly spaced range of numbers. The most straightforward option that Python offers is the built-in range().
🌐
AskPython
askpython.com › python-modules › numpy › numpy-linspace-python
NumPy linspace(): Create Arrays Fast - AskPython
January 25, 2026 - The np.linspace function generates evenly spaced numbers across a defined interval. You specify where to start, where to stop, and how many values you want.
🌐
GitConnected
levelup.gitconnected.com › the-fastest-way-to-generate-a-sequence-in-python-a61da7f87852
The fastest way to generate a sequence in Python | by Astronomy not Astrology, hunty... | Level Up Coding
May 14, 2020 - The built-in method range([start, ]stop, [step]) was my first introduction to generating sequences in Python. The optional arguments in the function are shown in square brackets. The range() method generates an immutable object that is a sequence of numbers.
🌐
w3resource
w3resource.com › python-exercises › data-structures-and-algorithms › python-search-and-sorting-exercise-2.php
Python: Sequential search - w3resource
July 28, 2025 - Sequential Search: In computer science, linear search or sequential search is a method for finding a particular value in a list that checks each element in sequence until the desired element is found or the list is exhausted.
🌐
Programiz
programiz.com › dsa › linear-search
Linear Search (With Code)
# Linear Search in Python def linearSearch(array, n, x): # Going through array sequencially for i in range(0, n): if (array[i] == x): return i return -1 array = [2, 4, 0, 1, 9] x = 1 n = len(array) result = linearSearch(array, n, x) if(result == -1): print("Element not found") else: print("Element found at index: ", result) // Linear Search in Java class LinearSearch { public static int linearSearch(int array[], int x) { int n = array.length; // Going through array sequencially for (int i = 0; i < n; i++) { if (array[i] == x) return i; } return -1; } public static void main(String args[]) { in
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.linspace.html
numpy.linspace — NumPy v2.1 Manual
The end value of the sequence, unless endpoint is set to False. In that case, the sequence consists of all but the last of num + 1 evenly spaced samples, so that stop is excluded.
🌐
Lawrence
www2.lawrence.edu › fast › GREGGJ › Python › classes › Classes.html
Classes
This is a simple mathematical formula that generates a sequence of integers. To form the sequence we pick an arbitrary integer as the seed for the sequence. We then substitute that starting value into a simple linear function to generate the next number in the sequence.
🌐
Python Like You Mean It
pythonlikeyoumeanit.com › Module3_IntroducingNumpy › FunctionsForCreatingNumpyArrays.html
Functions for Creating NumPy Arrays — Python Like You Mean It
>>> import numpy as np # creating an array from a Python sequence >>> np.array([i**2 for i in range(5)]) array([ 0, 1, 4, 9, 16]) # creating an array filled with ones >>> np.ones((2, 4)) array([[ 1., 1., 1., 1.], [ 1., 1., 1., 1.]]) # creating an array of evenly-spaced points >>> np.linspace(0, 10, 5) array([ 0.