Represent Immutable Vectors in Python



Immutable Vector in Python

An immutable vector in Python is a fixed, ordered collection of numerical values that cannot be changed after creation. These are implemented using a tuple or libraries like immutable arrays, which specify data consistency, preventing modifications during computations.

Representing Immutable Vectors

Immutable vectors can be represented using tuples, which define ordered and unchangeable values. Alternatively, libraries like NumPy allow the creation of arrays with writable=False, making them immutable. This ensures that the vector values remain constant. Here are the methods to represent immutable vectors in Python.

  • Using a Tuple

  • Using NumPy Arrays

Using a Tuple

A tuple is an immutable data structure in Python. It is one of the best choices to implement an immutable vector in Python.

Example

This code defines a tuple named vector with three float values, representing a fixed collection -

vector = (3.0, 4.0, 5.0)
print(vector)

Following is the output of the above program -

(3.0, 4.0, 5.0)

Using NumPy Arrays

In Python, we often use a library called NumPy when we need to work with numbers, like lists of numbers or grids of numbers. Normally, these NumPy lists can be changed any time; we can update these numbers inside them as we like.

Sometimes, we don't want to allow any changes to these numbers after they are created. This is useful when the numbers are important, and these should stay the same while the program is running. We can lock an array so this can change by setting writebale to False.

Example

Following is an example of creating an immutable array using NumPy arrays -

import numpy as np
vector = np.array([4.0, 5.0, 6.0])
vector.flags.writeable = False
print(vector)
print(vector.flags.writeable)

Following is the output of the above program -

[4. 5. 6.]
False

Now, if we try to change a number in the list, an error is generated. This ensures our important numbers remain safe from accidental changes.

Updated on: 2025-04-15T18:06:22+05:30

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements