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'])
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!
What is wrong with:
L.append('a1')
or
L += ['a1', 'a2']
to append items to a list, you can use +
L + ["a1","a2"]
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 the extend method
L = ['abc', 'ADB', 'aBe']
L.extend(['a1', 'a2'])
L.extend(['a3', 'a4'])
精彩评论