1

Possibly wrong terminologies here, please correct me.

Problem:
I have many objects, say lists of integers a=[1,3,7], b=[1,9], c... etc. I want to convert each to an np.array for instance.

So far:
What works: Explicitly convert individually:

a=np.array(a)
b=np.array(b)
...

What did not work:
[np.array(x) for x in [a,b,c...]] which only gives a list of the arrays (ok, that was expected) but does not change the variable a,b... to be of type np.array.

I am aware this unveils how little I know about python basics (what is pointer, what is reference etc...too long ago where I learned about it for c++).

3
  • 1
    a,b,c = [np.array(x) for x in [a,b,c...]][np.array(x) for x in [a,b,c]] (but i second chepners comment) Commented Dec 22, 2021 at 20:53
  • 7
    Obligatory reading: nedbatchelder.com/text/names.html. You probably don't want individual names in the first place, but a dict whose keys you can iterate over in order to reassign to the same keys. for k, v in d.items(): d[k] = np.array(v). Commented Dec 22, 2021 at 20:53
  • Type casting, in the sense of changing the type of an object, does not generally work in Python. In some cases you can change the .__class__ of an object, but that won't work between lists and arrays. Commented Dec 22, 2021 at 20:57

1 Answer 1

2

You have the right idea, but as you've seen, np.array(x) will create a new array based on x, not modify x itself. Having said that, you can assign these values back to the original variables:

a,b,c,etc=[np.array(x) for x in [a,b,c,etc]] 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.