How to append multiple items in one line in Python
No.
First off, append
is a function, so you can't write append[i+1:i+4]
because you're trying to get a slice of a thing that isn't a sequence. (You can't get an element of it, either: append[i+1]
is wrong for the same reason.) When you call a function, the argument goes in parentheses, i.e. the round ones: ()
.
Second, what you're trying to do is "take a sequence, and put every element in it at the end of this other sequence, in the original order". That's spelled extend
. append
is "take this thing, and put it at the end of the list, as a single item, even if it's also a list". (Recall that a list is a kind of sequence.)
But then, you need to be aware that i+1:i+4
is a special construct that appears only inside square brackets (to get a slice from a sequence) and braces (to create a dict
object). You cannot pass it to a function. So you can't extend
with that. You need to make a sequence of those values, and the natural way to do this is with the range
function.
You could also:
newlist += mylist[i:i+22]
No. The method for appending an entire sequence is list.extend()
.
>>> L = [1, 2]
>>> L.extend((3, 4, 5))
>>> L
[1, 2, 3, 4, 5]