Python += with a list and a tuple -
this question has answer here:
- why += behave unexpectedly on lists? 7 answers
- why can't add tuple list '+' operator in python? 3 answers
i saw wrote interesting python line online, couldn't understand why works. can try following lines in python interpreter:
s=[1] s=s+(1,-1)
this result in error "typeerror: can concatenate list (not "tuple") list". if done in way:
s=[1] s+=(1,-1)
will result in s = [1,1,-1]
so used thought x=x+y equivalent x+=y, can tell me how different , why second way works? in advance.
instead of +=
use list.extend
:
s = [1] s.extend((1,-1))
Comments
Post a Comment