Today I noticed a strange behavior while doing some python list operations.
Lets say,
a = []
b = 'xy'
When I do, a += b the interpreter returns:
a += b
a == ['x', 'y']
but when I do, a += b, (with a comma) the interpreter returns a = ['xy']
a += b,
a == ['xy']
Can someone please explain what is happening here.
a += b
When a is a list, this operation is similar to a.extend(b). So it iterates the object b, appending each element to a.
If you iterate the string 'xy', it yields two elements 'x' and 'y'.
If you iterate the tuple 'xy',, it yields one element 'xy'.
The line
a += b,
is equivalent to
a += (b, )
It creates a tuple with one item. If it is added, the item 'xy' it added to a.
If you add a string like 'xy' it counts as a sequence of characters on it's own and every sequence item (character) is added individually to a.
So basically the comma wraps b into a tuple.
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