102
count = 0
i = 0
while count < len(mylist):
    newlist.append(mylist[i + 1])
    newlist.append(mylist[i + 2])
    # ...
    count = count + 1
    i = i + 12

I wanted to make the newlist.append() statements into a few statements.

2
  • Well obviously it's not the same if you get different results. Commented May 18, 2013 at 6:42
  • 4
    Assuming your objects are meant to be lists, your code is not valid Python as you are using [] instead of (). Please post real working code. Commented May 18, 2013 at 6:43

7 Answers 7

265

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]
Sign up to request clarification or add additional context in comments.

4 Comments

'insert' functions as 'append' but adds to the beginning of the list. Is there a function to adding multiple values to the beginning of a list?
@sparrow: No. Slice-assign instead.
do you need the second input to be a list or can it just be each element separated by commas?
@CharlieParker: The argument to list.extend() must be an iterable.
5

You could also:

newlist += mylist[i:i+22]

Comments

3
mylist = [1,2,3]

def multiple_appends(listname, *element):
    listname.extend(element)

multiple_appends(mylist, 4, 5, "string", False)
print(mylist)

OUTPUT:

[1, 2, 3, 4, 5, 'string', False]

Comments

2
L1 = [1, 2]
L2 = [3,4,5]

L1+L2

#Output
[1, 2, 3, 4, 5]

By using the (+) operator you can skip the multiple append & extend operators in just one line of code and this is valid for more then two of lists by L1+L2+L3+L4.......etc.

Comments

1

If you are adding the same element then you can do the following:

["a"]*2
>>> ['a', 'a']

Comments

1

Use a for loop, it might look like this:

for x in [1,2,7,8,9,10,13,14,19,20,21,22]:
    new_list.append(my_list[i + x])

Comments

0

Pretty simple. Surprisingly in python, you can just use +=

myList += newListItems

Example

myList = [1,2]
myList += [3,4]

print(myList) # prints [1,2,3,4]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.