Mr.Bagel
Mr.Bagel

Reputation: 33

difference between += and append in python nested list concatenating

for example:

re=[]
for i in range(5):
    #fill code here

my question is, what does the comma do in #4 ? I always thought a trailing comma will make them into tuples, but they are lists apparently. So I also tried "re+=i,", and re will still be the list: [0,1,2,3,4]

then I did another try with the following:

re=[]
re=re+[1]

and now re=[1] if I do:

re=[]
re=re+[1], 

then re=([1],), and re now is a tuple, no longer a list

and finally if I do:

re=[]
for i in range(5):
    re=re+[i]

re is now [0,1,2,3,4]

but if I changed it to:

re=[]
for i in range(5):
    re=re+[i],

now I get: TypeError: can only concatenante tuple (not "list") to tuple

Could anyone explain it to me what's going on here ? I tried googling for answers, but no one seems to talk about this

Upvotes: 2

Views: 92

Answers (1)

Barmar
Barmar

Reputation: 781004

[i], is equivalent to ([i],), which is a tuple with one element, and that element is the list [i].

When you concatenate any sequence to a list with +=, it iterates over the sequence and appends each element to the list. So

re += [i],

is equivalent to

for x in ([i],):
    re.append(x)

Since there's only one element in ([i],), this is further equivalent to:

re.append([i])

which is what you have in #2, so you get the same result.

Upvotes: 2

Related Questions