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.
1 Answer 1
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.
t = s[:]might make sense if you're writing generic code and all you know is thatsis a sequence. Then if you want a copy with the same type as the original you writes[:]. But for a string in particular there's no need for a copy.