L = ['abc', 'ADB', 'aBe']
L[len(L):]=['a1', 'a2'] # append items at the end...
L[-1:]=['a3', 'a4'] # append more items at the end...
... works, but 'a2' is missing in the output:
['abc', 'ADB', 'aBe', 'append', 'a1', 'a3', 'a4']
L = ['abc', 'ADB', 'aBe']
L[len(L):]=['a1', 'a2'] # append items at the end...
L[-1:]=['a3', 'a4'] # append more items at the end...
... works, but 'a2' is missing in the output:
['abc', 'ADB', 'aBe', 'append', 'a1', 'a3', 'a4']
I think that the -1 is pointing at the last element of the list, which gets overwritten by 'a3'. As described here, you can do a
list.extend(['a3', 'a4'])
Your 3rd assignment is overwriting the 'a2' value.
Perhaps you should be using a more straightforward method:
L = ['abc', 'ADB', 'aBe']
L += ['a1', 'a2']
L += ['a3', 'a4']
Etc.
Use L.append
(for a single element) or L.extend
(for a sequence) -- there's absolutely no call for playing fancy "assign-to-slice" tricks (especially if you don't master them!-). The slice [-1:]
means "last element included onwards" -- so, by assigning to that slice, you're obviously "overwriting" the last element!
Use the extend method
L = ['abc', 'ADB', 'aBe']
L.extend(['a1', 'a2'])
L.extend(['a3', 'a4'])