Understanding the impact of Python variable assignment technique using the Fibonacci sequence
Tags: python, variableassignment, fibonacci, variables
Published: 2023-05-26 08:10:43

---
title: Understanding the impact of Python variable assignment technique using the Fibonacci sequence
published: true
date: 2023-05-26 07:59:40 UTC
tags: #python #variableassignment #fibonacci #variables
canonical_url: https://salwoch.hashnode.dev/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](https://en.wikipedia.org/wiki/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](https://code.visualstudio.com/) installed on your computer or online IDE such as [replit](https://replit.com/)

- 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1685024258257/302ca5a0-e741-4c7d-98b3-a5feb5ce989c.png)

## multiple variable assignment

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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1685025201831/6910d860-f303-4944-8f4f-c8cdc7747671.png)

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:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1685025684222/6eb9cfdf-8080-4d8b-8202-5bb6b80d565a.png)

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](https://en.wikipedia.org/wiki/Integer_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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1685034908812/d65a12d8-beac-4d5c-bd23-874e0c0324ed.png)

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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1685036131839/4eadb206-82a3-4d6e-a629-c009c8ce2231.png)

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

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1685080509283/2e06b4c6-d466-46b7-a4c1-6df99e59580e.png)

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 made 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:

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1685084310246/2a0d099a-f425-4172-a0f7-b50e361c358d.png)

## 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.