Corey
Corey

Reputation: 6842

Adding elements to a tuple when I know I shouldn't be able to

Dive Into Python is one of many sources that says:

You can't add elements to a tuple.

But it looks as if I was allowed to do just that. My code:

from string import find

def subStringMatchExact(target, key):
    t = (99,)
    location = find(target, key)
    while location != -1
        t += (location,)    # Why is this allowed?
        location = find(target, key, location + 1)
    return t

print subStringMatchExact("atgacatgcacaagtatgcat", "tg")

Output:

(99, 1, 6, 16)

This leads me to believe that I am not actually creating a tuple when I initialize t. Can someone help me understand?

Upvotes: 5

Views: 9276

Answers (3)

Lee
Lee

Reputation: 144206

t += (location,) is a shorthand for t = t + (location,) so you are creating a new tuple instance and assigning that to t each time around the loop.

Upvotes: 3

manji
manji

Reputation: 47968

You are concatenating 2 tuples in a new one. You are not modifying the original.

> a = (1,)
> b = a
> b == a
True
> a += (2,)
> b == a
False

Upvotes: 12

Dan Breen
Dan Breen

Reputation: 12934

My guess is that you're just creating a new instance of a tuple and assigning it to t. It's not actually modifying the original t object.

Upvotes: 2

Related Questions