Open In App

Cloning Row and Column Vectors in Python

Last Updated : 21 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, cloning row or column vectors involves creating a duplicate copy of a one-dimensional array (vector) either horizontally (row) or vertically (column). Cloning vectors is important for preserving data integrity and avoiding unintended modifications to the original array. In this article, we will explore different approaches to clone row or column vectors in Python.

Cloning Row and Column Vectors In Python

Below are the possible approaches to clone row or column vectors in Python:

  • Using List Slicing
  • Using NumPy’s copy Function

Cloning Row and Column Vectors Using List Slicing

In this approach, we are using list slicing (originalVect[:]) to clone the original row vector, creating a new list with the same elements. Additionally, we use a list comprehension ([[x] for x in originalVect]) to create a cloned column vector by wrapping each element of the original vector in a sublist.

Python3
originalVect = [1, 2, 3, 4]
clonedRowVect = originalVect[:]

clonedColumnVect = [[x] for x in originalVect]

print("Original Row Vector:", originalVect)
print("Cloned Row Vector:", clonedRowVect)
print("Cloned Column Vector:")

for row in clonedColumnVect:
    print(row)
    

Output
Original Row Vector: [1, 2, 3, 4]
Cloned Row Vector: [1, 2, 3, 4]
Cloned Column Vector:
[1]
[2]
[3]
[4]

Cloning Row and Column Vectors Using NumPy’s copy() Function

In this approach, we are using NumPy’s copy function to create a shallow copy of the original vector originalVect, resulting in the cloned row vector clonedRowVect. Additionally, for cloning a column vector, we use np.copy on the original vector with the [:, np.newaxis] indexing to add a new axis, creating the cloned column vector clonedColumnVect.

Python3
import numpy as np

originalVect = np.array([1, 2, 3, 4])

clonedRowVect = np.copy(originalVect)
clonedColumnVect = np.copy(originalVect[:, np.newaxis])

print("Original Row Vector:", originalVect)
print("Cloned Row Vector:", clonedRowVect)
print("Cloned Column Vector:")

print(clonedColumnVect)

Output
Original Row Vector: [1 2 3 4]
Cloned Row Vector: [1 2 3 4]
Cloned Column Vector:
[[1]
 [2]
 [3]
 [4]]

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads