Steve
Steve

Reputation: 5073

What's this syntax in python mean?

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.

Upvotes: 0

Views: 139

Answers (1)

Steve Jessop
Steve Jessop

Reputation: 279385

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.

Upvotes: 7

Related Questions