tags:

views:

70

answers:

6
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']
+1  A: 

What is wrong with:

L.append('a1')

or

L += ['a1', 'a2']
DoR
append, but I'm learning so testing out various method; + creates a new list so its slower than changing in-place.
Nimbuz
+ may create a new list, but += as posted by @Pynt does not.
Paul McGuire
A: 

to append items to a list, you can use +

L + ["a1","a2"]
ghostdog74
+3  A: 

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'])
Kaleb Brasee
Nice catch. +1 -
MitMaro
A: 

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.
Peter Rowell
+3  A: 

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!

Alex Martelli
A: 

Use the extend method

L = ['abc', 'ADB', 'aBe']
L.extend(['a1', 'a2'])
L.extend(['a3', 'a4'])
Dominic Bou-Samra