If tuples are immutable lists, then how is the following possible? lets set an empty tuple n. n = () for i in range(0, 5): n += (i, ) n will return the value (0, 1, 2, 3, 4) we just added element values 0-4 to something thats not supposed to be able to add or remove elements. Is my understanding of immutability just plain wrong here?
I think 'var += x' is a shortcut for var = var + x, this creates a new variable using the old one as a base. mutability refers to methods, var.append(x) for example. This is significant in many places, you'll have to learn those on your own. play around with id(y) it translated the value y into a number. you can see when your creating a new list, and when your editing an existing one.
As Nessman hinted at, you are assigning something new to n each time, the value of an expression that contains a tuple, but you're not mutating the tuple. You can do >>>string = 'abc' >>>string += 'd' >>>print string abcd even though strings are immutable.
I think there is a hint somewhere in lectures 5-7. It was said that the interpreter destroys the link to the old value and creates a link to the new value of the variable; whereas if an object is mutable the link is not destroyed and values can be changed directly without destroying the links... As far as I understood it.
to get a better ideas of this linking that vaboro mentions. I made a little example >>> List = [1,2,3] >>> Tuple = (1,2,3) >>> def mutate(List, Tuple): List += [4,] Tuple += (4,) print List print Tuple >>> mutate(List,Tuple) [1, 2, 3, 4] (1, 2, 3, 4) >>> List [1, 2, 3, 4] >>> Tuple (1, 2, 3) >>> as you hopefully know, everything done inside a def <name> is in an "isolated" environment. (if you don't know this, it gets explained in a later lecture) this means that any variables created in this environment don't leave the environment. the reason why the list was changed outside the environment was because no new link was created, it edited what was at the end of the original link. this is one of the reasons mutability matters, another is ease of modification. for example >>> List.insert(2,2.5) >>> List [1, 2, 2.5, 3, 4] Try doing that with a tuple and you get an error, fun stuff. Its rather late for me so i hope that was clear, apologies if its not.
It's pretty simple. You can use an immutable object as a value or as part of an expression, but you can't mutate the object. The number 2 is an immutable object, but we can use it to create new objects by using the 2 as a value a = 2 or as part of an expression a = 2 + 2 The 2 never mutates.
A list will mutate, so you can do >>>a = [1] >>>a.append(2) >>>print a [1, 2] >>> You can't do that with a tuple, but you mutate a list using a tuple as the value or part of an expression. >>>a = [1] >>>b = ('a tuple', 'with two strings in') >>>a.append(b) >>>print a [1, ('a tuple', 'with two strings in')] The tuple never mutates.
Join our real-time social learning platform and learn together with your friends!