3

Python lists have a += operator as well as append and extend methods.

If l is a list, is l += ... equivalent to l.append(...), l.extend(...), both, or neither?

user200783
  • 13,722
  • 12
  • 69
  • 135
  • 2
    Did you try it? `l += 4` gives an error; `l += [4]` adds `4` to the list. – zondo Apr 10 '16 at 01:53
  • You can find out what various expressions evaluate to by entering them into the Python interpreter. Feel free to play around with it and try different things (I do this often; it's helpful). – TigerhawkT3 Apr 10 '16 at 02:01
  • 3
    When applied to a list, `+=` is mostly equivalent to `extend`, but there can be some subtle scoping differences in a function context in the absence of `global` and `nonlocal`. In this case, `+=` will force the creation of a local, while `extend` will not. – Tom Karzes Apr 10 '16 at 02:56

1 Answers1

12

In python += on a list is equivalent to extend method on that list.

Shiv
  • 1,912
  • 1
  • 15
  • 21