side effect gotchas in python/numpy? horror stories and narrow escapes wanted

Posted by shabbychef on Stack Overflow See other posts from Stack Overflow or by shabbychef
Published on 2010-03-09T18:19:54Z Indexed on 2010/04/16 18:53 UTC
Read the original article Hit count: 342

I am considering moving from Matlab to Python/numpy for data analysis and numerical simulations. I have used Matlab (and SML-NJ) for years, and am very comfortable in the functional environment without side effects (barring I/O), but am a little reluctant about the side effects in Python. Can people share their favorite gotchas regarding side effects, and if possible, how they got around them? As an example, I was a bit surprised when I tried the following code in Python:

lofls = [[]] * 4    #an accident waiting to happen!
lofls[0].append(7)  #not what I was expecting...
print lofls         #gives [[7], [7], [7], [7]]
#instead, I should have done this (I think)
lofls = [[] for x in range(4)]
lofls[0].append(7)  #only appends to the first list
print lofls         #gives [[7], [], [], []]

thanks in advance

© Stack Overflow or respective owner

Related posts about python

Related posts about side-effects