Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between list += str and list += str,

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.

like image 728
Pritam Avatar asked Nov 19 '25 03:11

Pritam


2 Answers

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

like image 184
wim Avatar answered Nov 20 '25 18:11

wim


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.

like image 33
Klaus D. Avatar answered Nov 20 '25 17:11

Klaus D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!