I was looking at code in my course material and had to write a function which adds the value 99 to either a list
or tuple
. The final code looks like this:
def f(l):
print(l)
l += 99,
print(l)
f([1,2,3])
f((1,2,3))
This was used to show something different but I'm getting somewhat hung up on the line l += 99,
. What this does, is create an iterable that contains the 99 and list
as well as tuple
support the simple "addition" of such an object to create a new instance/add a new element.
What I don't really get is what exactly is created using the syntax element,
? If I do an assignment like x = 99,
the type(x)
will be tuple
but if I try run x = tuple(99)
it will fail as the 99 is not iterable. So is there:
element,
?tuple
without an iterable and somehow ,
is mapped to that?Edit:
In case anyone wonders why the accepted answer is the one it is: The explanation for my second question made it. I should've been more clear with my question but that +=
is what actuallly got me confused and this answer includes information on this.
If the left-hand argument of =
is a simple name, the type of argument currently bound to that name is irrelevant. tuple(99)
fails because tuple
's argument is not iterable; it has nothing to do with whether or not x
already refers to an instance of tuple
.
99,
creates a tuple with a single argument; parentheses are only necessary to separate it from other uses of commas. For example, foo((99,100))
calls foo
with a single tuple argument, while foo(99,100)
calls foo
with two distinct int
arguments.
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