How to add multiple elements to one line in Python

I have:

count = 0 i = 0 while count < len(mylist): if mylist[i + 1] == mylist[i + 13] and mylist[i + 2] == mylist[i + 14]: print mylist[i + 1], mylist[i + 2] newlist.append(mylist[i + 1]) newlist.append(mylist[i + 2]) newlist.append(mylist[i + 7]) newlist.append(mylist[i + 8]) newlist.append(mylist[i + 9]) newlist.append(mylist[i + 10]) newlist.append(mylist[i + 13]) newlist.append(mylist[i + 14]) newlist.append(mylist[i + 19]) newlist.append(mylist[i + 20]) newlist.append(mylist[i + 21]) newlist.append(mylist[i + 22]) count = count + 1 i = i + 12 

I wanted to make the newlist.append() statements in several statements.

+80
python
May 18 '13 at 6:41
source share
4 answers

No. Method to add an entire sequence list.extend() .

 >>> L = [1, 2] >>> L.extend((3, 4, 5)) >>> L [1, 2, 3, 4, 5] 
+198
May 18 '13 at 6:43
source share

No.

First of all, append is a function, so you cannot write append[i+1:i+4] because you are trying to get a fragment of a thing that is not a sequence. (You cannot get an element from it: append[i+1] is wrong for the same reason.) When you call a function, the argument goes into parentheses, that is, round: () .

Secondly, what you are trying to do is "take the sequence and put each element in it at the end of this other sequence in the original order." It is written extend . append : "Take this thing and put it at the end of the list as one item , even if it is also a list." (Recall that a list is a kind of sequence.)

But then you need to know that i+1:i+4 is a special construction that appears only inside square brackets (to get a fragment from a sequence) and curly braces (to create a dict object). You cannot pass it to a function. So you cannot extend with this. You need to make a sequence of these values, and the natural way to do this is with the range function.

+5
May 18 '13 at 7:11
source share

You also can:

 newlist += mylist[i:i+22] 
+4
Feb 28 '14 at
source share
 mylist = [1,2,3] def multiple_appends(listname, *element): listname.extend(element) multiple_appends(mylist, 4, 5, "string", False) print(mylist) 

EXIT:

 [1, 2, 3, 4, 5, 'string', False] 
0
Mar 21 '19 at 10:11
source share



All Articles