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.
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.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With