me, thinking out loud…

If you are new to Python, you should probably stop reading here. But, if you have used Python and numpy, then read on. Before, that try these bits of code.

import numpy
a = numpy.array([1,2])
a = a + 0.5j 
print a
[ 1.+0.5j  2.+0.5j]

The “same thing”, in a slightly different way.

import numpy
a = numpy.array([1,2])
a += 0.5j 
print a
[1 2]

Both the code blocks, look really the same, until you look carefully. Under normal circumstances a = a + b and a += b behave exactly similarly, and we really don’t need to bother about the differences between them.

But, +=, which is an augmented assignment operator, actually tries to perform the operation in-place, unlike the other statement where + actually returns a new object which is again being referenced by the name a.

But, when dealing with numpy arrays, this will lead to trouble. When assigning to an array, it’s dtype is not changed and hence the trouble.

The right way to use the augmented assignment operator, would be:

import numpy
a = numpy.array([1,2], dtype=complex)
a += 0.5j 
print a
[ 1.+0.5j  2.+0.5j]

The same thing is explained in this thread. Also, Thanks to Bhanukiran for asking me this.

About these ads

Comments on: "Augmented assignment in Python" (3)

  1. ok, I stopped reading when you asked me to. Next what should I do? :P

  2. Interesting, never came across this concept.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Tag Cloud

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: