Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

tuples

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?

like image 835
Corey Avatar asked Apr 22 '11 15:04

Corey


People also ask

Can we add an element to a tuple if yes how if no why?

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.

Can you add things to a tuple?

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.

How do you add elements to a tuple in Python?

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.

Why tuples Cannot be edited?

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).


2 Answers

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
like image 182
manji Avatar answered Oct 14 '22 21:10

manji


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.

like image 34
Lee Avatar answered Oct 14 '22 22:10

Lee