Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to append multiple lists at once? (Python)

I have a bunch of lists I want to append to a single list that is sort of the "main" list in a program I'm trying to write. Is there a way to do this in one line of code rather than like 10? I'm a beginner so I have no idea...

For a better picture of my question, what if I had these lists:

x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] 

And want to append y and z to x. Instead of doing:

x.append(y) x.append(z) 

Is there a way to do this in one line of code? I already tried:

x.append(y, z) 

And it wont work.

like image 791
anon Avatar asked Jan 03 '13 00:01

anon


People also ask

Can I append multiple things 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.

Can you append lists to lists in Python?

append() adds a list inside of a list. Lists are objects, and when you use . append() to add another list into a list, the new items will be added as a single object (item).


2 Answers

x.extend(y+z) 

should do what you want

or

x += y+z 

or even

x = x+y+z 
like image 83
Joran Beasley Avatar answered Oct 03 '22 14:10

Joran Beasley


You can use sum function with start value (empty list) indicated:

a = sum([x, y, z], []) 

This is especially more suitable if you want to append an arbitrary number of lists.

like image 42
Minjoon Seo Avatar answered Oct 03 '22 14:10

Minjoon Seo