I recently started coding in Python 2.7. I'm a molecular biologist. I'm writing a script that involves creating lists like this one:
mylist = [[0, 4, 6, 1], 102]
These lists are incremented by adding an item to mylist[0] and summing a value to mylist[1].
To do this, I use the code:
def addres(oldpep, res):
return [oldpep[0] + res[0], oldpep[1] + res[1]]
Which works well. Since mylist[0] can become a bit long, and I have millions of these lists to take care of, I thought that using append or extend might make my code faster, so I tried:
def addres(pep, res):
pep[0].extend(res[0])
pep[1] += res[1]
return pep
Which in my mind should give the same result. It does give the same result when I try it on an arbitrary list. But when I feed it to the million of lists, it gives me a very different result. So... what's the difference between the two? All the rest of the script is exactly the same. Thank you! Roberto
a.append(b)
modifies the lista
to have an extra element, wherea += [b]
creates a new list containing the contents ofa
followed by the elementb
, and then assigns it to the namea
. If nobody else is using the list that used to be calleda
, it's then thrown away, for the same net effect. The problem is that in your code, apparently, someone else is still using the old list by that name.