Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append multiple items in one line in Python

Tags:

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 into a few statements.

like image 840
whatever Avatar asked May 18 '13 06:05

whatever


People also ask

Can you append multiple items at once Python?

You can use the sequence method list. extend to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values. So you can use list. append() to append a single value, and list.


2 Answers

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] 
like image 141
Ignacio Vazquez-Abrams Avatar answered Oct 07 '22 01:10

Ignacio Vazquez-Abrams


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.

like image 22
Karl Knechtel Avatar answered Oct 07 '22 02:10

Karl Knechtel