Understanding the impact of Python variable assignment technique using the Fibonacci sequence

Understanding the impact of Python variable assignment technique using the Fibonacci sequence

Python offers two ways to assign variables; single and multiple variable assignment. The choice of which variable assignment technique you use sometimes has a tremendous effect on your code's accuracy.

This article will explain the two variable assignment methods and will use the Fibonacci sequence to illustrate the variation in results caused by each of them.

Prerequisites

To follow along, you should have:

  • A code editor such as VScode installed on your computer or online IDE such as replit

  • Python installed if you're using a code editor locally on your machine.

single variable assignment

Under single variable assignment, only a single value is assigned to a single variable as follows:

x=5

If under the first x variable assignment, you reinitialised x with the value 10 and printed it, the previous value would be overwritten and you'd have 10 as the new value of x as shown below:

variable reassignment

multiple variable assignment

Under multiple variable assignment, multiple variables can reference a single value as shown below:

variable assignment in Python follows the right-to-left rule and what happens in this case is that the value 10 is first assigned to the variable r, then r assigned to q and finally, q gets assigned to p.

Also under multiple variable assignment, multiple values can be assigned to multiple variables on a single line as shown below:

In the above example, a tuple of (5,10,15) is created and iterated over to assign the values to a,b and c

Now you must be thinking "Oh I could just choose the single variable assignment and stick with it" -but sometimes it's not one size fits all. Depending on the problem, a change in variable assignment may be required to attain the desired level of accuracy.

The Fibonacci Sequence

In mathematics, the Fibonacci Sequence is a sequence in which each number is the sum of the two preceding ones. Numbers that are part of the Fibonacci sequence are known as Fibonacci numbers. The sequence commonly starts from 0 and 1, although some authors start the sequence from 1 and 1 or sometimes (as did Fibonacci) from 1 and 2. Starting from 0 and 1, the first few values in the sequence are:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144.

- Wikipedia

To break it down, there are two initial numbers in the sequence; 0 and 1. The next Fibonacci number is the sum of 0 and 1 which is 1. The sequence now consists of 0,1,1. The next number would be a sum of the last two numbers in the sequence - 1 and 1 to make it 0,1,1,2 and so on....

In this example, the goal is to write a function with a parameter n -that will generate Fibonacci numbers using n as the limit. The steps to achieve this are broken down as follows:

  1. create variables x and y to store the initial values 0 and 1 respectively

  2. create an empty array for the Fibonacci numbers

  3. loop through the limit to add the Fibonacci numbers

  4. in the loop, set x to the value y and y to the sum of x and y

  5. return the array of Fibonacci numbers

The above pseudo-code now becomes:

def generate_fibonacci(n):
  x= 0
  y=1
  fibs = []
  while x < n:
    fibs.append(x)
    x = y
    y = x + y
  return fibs

print(generate_fibonacci(100))

When you run this code, you should have the following result in your terminal

Just to be sure the function is returning accurate results, add a unit test to test its output

import unittest

class FibonacciGeneratorTest(unittest.TestCase):

  def test_generate_fibonacci(self):
    # Test the Fibonacci generator for various inputs
    test_cases = [(0, []), (1, [0]), (2, [0, 1, 1]),
                  (10, [0, 1, 1, 2, 3, 5, 8]),
                  (100, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89])]

    for n, expected_sequence in test_cases:
      with self.subTest(n=n):
        self.assertEqual(generate_fibonacci(n), expected_sequence)

if __name__ == '__main__':
  unittest.main()

In the above code, we import the unittest module and write a test for the generate_fibonacci function. An array of test cases is added with the limit being the first item in each tuple and the expected Fibonacci sequence as the second item. We then loop over the test cases and assert that the value returned from generate_fibonacci(n) is equal to the expected Fibonacci sequence.

Run the test and you should have a result in the teminal

Well, looks like the test failed! An indicator that the generate_fibonacci function is not working as expected and will need to be refactored to provide the desired result.

When you critically look at the sequence from the generate_fibonacci function, you can observe that the proceeding numbers are multiples of the preceding numbers -implying the problem could be in the while loop.

def generate_fibonacci(n):
#.....
  while x < n:
    fibs.append(x)
    x = y
    y = x + y
  #......

from the while loop, after appending the initial x value (0) to the fibs array, x is set to the value of y (1); y becomes the sum of 1 and 1 -adding 1 to the sequence. Thereafter, subsequent iterations generate multiples of the preceding number. This is not what we're trying to achieve!

To solve the above problem, refactor the code using multiple variable assignment:

def generate_fibonacci(n):
  x = 0
  y = 1
  fibs = []
  while x < n:
    fibs.append(x)
    x, y = y, x + y
  return fibs

print(generate_fibonacci(100))

Run the code and you should have a result in your terminal

Now you have an accurate list of Fibonacci numbers of the specified limit and the test passed too!

So what changed? Well, using multiple variable assignment makes it possible to assign new values to x and y based on their existing values. In the previous implementation, reassigning the value of x separately from y meant y would become the sum of the new value of x and y -providing inaccurate results.

Besides reassigning variables based on their existing values, the multiple variable assignment technique is also commonly used when swapping values between variables as shown below:

Conclusion

If you made it this far you've understood Python variable assignment methods and how each of the methods is likely to impact your code's accuracy.