2 Easy Ways to Create a Vector in Python

Python does not have a built-in Vector data structure. However, use a third-party library such as numpy to create a vector and perform different operations on the vector.

What is Python Vector?

Python vector is a data structure that represents a sequence of elements. It can be as simple as a list or an array in Python.

How to Create a Vector in Python

2 Easy ways to create a vector in Python.

  1. Using list: By putting the elements into the square brackets([ ]), we can create a vector in Python.
  2. Using numpy array: The np.array() function returns the vector containing array elements.

Method 1: Using the list

To create a vector using the list in Python, use the square brackets and put the elements inside the list, and it will behave like a vector in Python.

# Define vector as a list
vector_1 = [19, 21, 11]

# printing two vectors using print() function
print(vector_1)

Output

[19, 21, 11]

You can see that a vector is a sequence of elements and a list, so here, we can use the list as a vector and perform different operations on the vector.

Method 2: Using np.array() function

To create a Vector in Python, use the np.array() function and pass the list of elements. To print the vector in the Python console, use the print() function.

import numpy as np

# Define vector as an array of numbers
vector = np.array([19, 21, 11])

# printing two vectors using print() function
print(vector)

Output

[19 21 11]

In this example, we create a vector called `vector` using the np.array() function. The np.array() function accepts a list of elements as input and returns a vector that contains those values. We then printed the vector to the console using the print() function.

Conclusion

The best and easiest way to create a vector in Python is to use the np.array() function from the numpy library.

Vectors are a valid data structure for storing and manipulating data sequences in Python. If you want to work with vectors in your Python code, use the numpy library or a similar library that provides vector data structures.

That’s it.

Further reading

Calculate the Distance Between Two Vectors in Python

Leave a Comment