Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semantics of python loops and strings

Consider:

args = ['-sdfkj']
print args
for arg in args:
    print arg.replace("-", '')
    arg = arg.replace("-", '')
print args

This yields:

['-sdfkj']
sdfkj
['-sdfkj']

Where I expected it to be ['sdfkj'].

Is arg in the loop a copy?

It behaves as if it is a copy (or perhaps an immutable thingie, but then I expect an error would be thrown...)

Note: I can get the right behavior with a list comprehension. I am curious as to the cause of the above behavior.

like image 768
Paul Nathan Avatar asked Jan 25 '26 21:01

Paul Nathan


2 Answers

Is arg in the loop a copy?

Yes, it contains a copy of the reference.

When you reassign arg you aren't modifying the original array, nor the string inside it (strings are immutable). You modify only what the local variable arg points to.

Before assignment         After assignment

args          arg          args          arg
  |            |            |            |
  |            |            |            |
(array)        /          (array)       'sdfkj'
  |[0]        /             |[0]        
   \         /              |
    \       /               |
     '-sdfkj'            '-sdfkj'
like image 129
Mark Byers Avatar answered Jan 27 '26 11:01

Mark Byers


Since you mention in your question that you know it can be done using list comprehensions, I'm not going to show you that way.

What is happening there is that the reference to each value is copied into the variable arg. Initially they both refer to the same variable. Once arg is reassigned, it refers to the newly created variable, while the reference in the list remains unchanged. It has nothing to do with the fact that strings are immutable in Python. Try it out using mutable types.

A non-list comprehension way would be to modify the list in place:

for i in xrange(len(args)):
    args[i]=args[i].replace('-','')
print args
like image 44
MAK Avatar answered Jan 27 '26 11:01

MAK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!