The Meaning Of += On List In Python
I'm currently working with graph traversal. find_path with path incremented like path = path + [start] returns [30, 3, 5, 8], whereas find_path2 with path incremented like path +=[
Solution 1:
One creates a new list (+), the other modifies the original list (+=):
In [28]: path = [30, 3, 4, 0, 1, 2, 5, 8]
In [29]: id(path)
Out[29]: 140580805174120
In [30]: path = path + [7] # assignment = new list
In [31]: id(path)
Out[31]: 140580805174840
In [32]: path = [30, 3, 4, 0, 1, 2, 5, 8]
In [33]: id(path)
Out[33]: 140580805175416
In [34]: path += [7] # same as list.extend, modifies list
In [35]: id(path)
Out[35]: 140580805175416
Also your mutable default arg will cause you trouble if you called the function twice you should use None as the arg value and set it to an empty list when you first call the function, not calling recursively:
deffind_path2(graph, start, end, path=None):
if path isNone:
path = []
That is actually somewhat the same as the difference between +=
and list = list + [value]
, the same object/list is used for repeated calls if you don't create a new object each time you call the function.
Solution 2:
path = path + [start]
creates a new list. Existing references to the list are not updated, whereas+=
modifies the list in-place.- Python has __iadd__so
+=
is more than just syntactic sugar.
Post a Comment for "The Meaning Of += On List In Python"