Tuples are immutable objects, that is, you cannot change the elements of the tuple once it is created, if you do want to change them it would be better to use a list
.
a = [3, 2]
for i in a:
i -= 1
print(a)
Which gives an output:
[3, 2]
Why didn't it work, even though list
s are mutable? And also, why doesn't your original code produce some kind of error, if tuple
s are really immutable? Well, this becomes more obvious if you write your for each
style loop as a simple for
:
for index in range(len(a)):
i = a[index]
i -= 1
print(a)
This code is just a more verbose version of your original example, but now the problem is clear - the code never actually changes the elements of the original list
. Instead, each iteration of the for
loop creates a new variable, i
, which takes its value from the correspondinglist
element. i -= 1
changes i
, not a[index]
.
Incidentally, that is why there is no error in your original code, even though tuple
s are supposed to be immutable - the code simply doesn't try to mutate the original tuple
at all.
A working example with a list would be something like:
a = [3, 2]
for index in range(len(a)):
a[index] -= 1
print(a)
which can be made more concise in the end by writing:
a = [3, 2]
a = [i - 1 for i in a]
print(a)
As an aside, if you really must take tuple
s as input and produce tuple
s as output, you can convert between tuple
s and list
s using the list
and tuple
functions. This is also why you shouldn't use tuple
as your variable name! Doing so will mean that you can't use that tuple
function in the same scope as your tuple
variable, making things very difficult and potentially confusing for you.