0

<class 'list'>'s insert method helps to add element ((1,2), (3, 4)) in a lst with expected output lst = [((1,2), (3, 4))],

lst = []
lst.insert(0, ((1,2), (3, 4)))
lst.insert(1, ((5, 6), (7, 8)))

But += operator does not give same result(lst = [(1, 2), (3, 4)]).

lst = []
lst += ((1,2), (3, 4))

+= operator internally calls __iadd__ method.

Why __iadd__ does not add element in a way class <'list'>'s insert(index,element) method does ? Because maintaining index needs extra name-value pair in my merge sort code is a big overhead..

overexchange
  • 15,768
  • 30
  • 152
  • 347
  • @SimeonVisser there is no fight between `+=` and `+` as shown in your old question. `+=` does not change the reference of `lst`, but how no change in reference has anything to do with adding element `((1,2), (3, 4))` – overexchange Jul 18 '15 at 18:02
  • @vaultah your old question recommends to use `extend` method. DO you think this is my question? – overexchange Jul 18 '15 at 18:09
  • Duplicate of [1](http://stackoverflow.com/q/20691982/2301450), [2](http://stackoverflow.com/q/7721192/2301450), [3](http://stackoverflow.com/q/15376509/2301450), [4](http://stackoverflow.com/q/13904039/2301450) and more – vaultah Jul 18 '15 at 18:16
  • The list `+=` operator doesn't add individual values but values from iterables. You can try `lst += [((1,2), (3, 4))]`, for example. – dlask Jul 18 '15 at 18:20

1 Answers1

1

x += y, where x and y are list-like will create a new list with the contents of y concatenated to the contents of x.

Since you don't want to append the contents of the tuple ((1,2), (3, 4)) to lst, instead want the tuple added to the list, you should lst.append(((1,2), (3, 4))) instead.

>>> lst = []
>>> lst.append(((1, 2), (3, 4)))
>>> lst.append(((5, 6), (7, 8)))
>>> lst
[((1, 2), (3, 4)), ((5, 6), (7, 8))]
Roshan Mathews
  • 5,788
  • 2
  • 26
  • 36