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?
You can't add elements to a tuple because of their immutable property. There's no append() or extend() method for tuples, You can't remove elements from a tuple, also because of their immutability.
In Python, since tuple is immutable, you cannot update it, i.e., you cannot add, change, or remove items (elements) in tuple . tuple represents data that you don't need to update, so you should use list rather than tuple if you need to update it.
To insert an element into a tuple in Python:Use the list() class to convert the tuple to a list. Use the list. insert() method to insert the element into the list. Use the tuple() class to convert the list to a tuple.
Tuples and lists are the same in every way except two: tuples use parentheses instead of square brackets, and the items in tuples cannot be modified (but the items in lists can be modified). We often call lists mutable (meaning they can be changed) and tuples immutable (meaning they cannot be changed).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With