开发者

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 ex开发者_Go百科pected 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.


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'


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


If you want to modify the actual list you have to specifically assign the changes to the list 'args.'

i.e.

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


for a list I'd try:

args = [x.replace("-", '') for x in args]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜