1

I have the following code in python:

a = "xxx" # a is a string
b = "yyy" # b is another string
for s in a, b:
 t = s[:]
 ...

I dont understand the meaning of for line. I know a, b returns a tuple. But what about looping through a, b? And why you need t = s[:]. I know s[:] creates a copy of list. But if s is a string, why don't you write t = s to make a copy of the string s into t?

Thank you.

asked Dec 22, 2013 at 10:53
3
  • 1
    Is this written by someone you think knows their stuff? The slice is pointless, but it's unclear whether that's because the person who wrote the code put in something pointless or because you simplified the code and missed something relevant. Commented Dec 22, 2013 at 11:07
  • ya i din't see any point or use case with the snippet. Commented Dec 22, 2013 at 11:07
  • Writing t = s[:] might make sense if you're writing generic code and all you know is that s is a sequence. Then if you want a copy with the same type as the original you write s[:]. But for a string in particular there's no need for a copy. Commented Dec 22, 2013 at 11:54

1 Answer 1

7

The meaning of the for loop is to iterate over the tuple (a, b). So the loop body will run twice, once with s equal to a and again equal to b.

t = s[:]

On the face of it, this creates a copy of the string s, and makes t a reference to that new string.

However strings are immutable, so for most purposes the original is as good as a copy. As an optimization, Python implementations are allowed to just re-use the original string. So the line is likely to be equivalent to:

t = s

That is to say, it will not make a copy. It will just make t refer to the same object s refers to.

answered Dec 22, 2013 at 11:00
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.