Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a set of Python lists to numpy arrays?

I need to set the type of a set of arrays to be of the type np.ndarray each one. Since I need to do it multiple times, I’m trying a for loop, it seems to be correctly converting from list to np.ndarray when executing the loop, but once it ends, each of the arrays are still of list type, this block below helped me to realize that it is happening, but I have no idea why it is happening

So, why is this happening? and how to fix it? Thanks in advance

import numpy as np

pos = [1,1,1]
vel = [1,1,2]
# vel = np.array([1,1,2])
accel = [1,1,3]

print('\nredefining...')
for elem in [pos,vel,accel]:
    # checks if the array is of the np.ndarray class
    print(type(elem))
    if not isinstance(elem, np.ndarray):
        elem = np.array(elem)
        print(type(elem))
    print('---------------------------')

print('\nafter the redefinition:')

print(type(pos))
print(type(vel))
print(type(accel))

output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

redefining...
<class 'list'>
<class 'numpy.ndarray'>
---------------------------
<class 'list'>
<class 'numpy.ndarray'>
---------------------------
<class 'list'>
<class 'numpy.ndarray'>
---------------------------

after the redefinition:
<class 'list'>
<class 'list'>
<class 'list'>

>Solution :

As Mark Tolonen noticed

import numpy as np

pos = [1, 1, 1]
vel = [1, 1, 2]
accel = [1, 1, 3]

arrays = [pos, vel, accel]

for i in range(len(arrays)):
    if not isinstance(arrays[i], np.ndarray):
        arrays[i] = np.array(arrays[i])

# Update the original variables
pos, vel, accel = arrays

print('\nAfter the redefinition:')
print(type(pos))   # <class 'numpy.ndarray'>
print(type(vel))   # <class 'numpy.ndarray'>
print(type(accel)) # <class 'numpy.ndarray'>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading