Python deleted my vector values

Sometimes scripting languages can be a real annoyance. Why? Because when you get as much help as you do with for instance Python, you also lose a lot of control.

Being used to scripting languages like PHP, I made the funny mistake today of initializing a set of arrays like:

a = v = r = zeros((n,2),float)

This seemed like a really good idea, saving me from typing two extra lines(!). As the sucker I am for short code I was happy with my newfound shortcut. What I didn’t realize is that Python, in comparison to PHP, treats assignments like these as pointers instead of variables.

I believed this would create three arrays with a lot of zeros in two dimensions as I would expect from PHP, but the result was that I instead created one array with loads of zeros in two dimensions, with three pointers a, v and r all pointing to the same array.

When I then started setting the values for each of these arrays using Euler’s method, the result was that I got a lot of nonsense in what I thought was three separate arrays.

As a reminder to myself and everyone else out there; Python is not PHP. If you want to initialize three arrays like this in Python, you’ll have to stick to  the long version:

a = zeros((n,2),float)
r = zeros((n,2),float)
v = zeros((n,2),float)

Or, you could at least save yourself from having to edit each assignment if you ever need to change the code by writing:

a = zeros((n,2),float)
r = a.copy()
v = a.copy()
This entry was posted in Programming, Python. Bookmark the permalink.

2 Responses to Python deleted my vector values

  1. Robert says:

    Hahaha, I bet you had one big WTF when you just got the same values again and again…

  2. Oh yes. It’s always funny to debug code which you believe is correct, when something like this makes it completely flawed. Having a paper due didn’t really help much either.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">