Home > front end >  difference between = and append in python nested list concatenating
difference between = and append in python nested list concatenating

Time:07-14

for example:

re=[]
for i in range(5):
    #fill code here
  • 1.) if we do "re.append(i)", re will be [0,1,2,3,4]
  • 2.) if we do "re.append([i])", re will be[[0],[1],[2],[3],[4]]
  • 3.) if we do "re =[i]", re will be [0,1,2,3,4]
  • 4.) if we do "re =[i],", yes, with a trailing comma, and re will be [[0],[1],[2],[3],[4]]

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

CodePudding user response:

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

  • Related