hald
hald

Reputation: 63

Python: create a list of lists

I have two list

l1= ["apple", "orange"]
l2 = ["red", green", "black", "blue"]

I want to create a list which appends both.

l3 = [["apple", "orange"], ["red", green", "black", "blue"]]. 

So the l3[0] =["apple", "orange"] and l3[1]=["red", green", "black", "blue"].

How do I do the above?

Upvotes: 2

Views: 102

Answers (5)

Haifeng Zhang
Haifeng Zhang

Reputation: 31915

Either:

>>> l1= ["apple", "orange"] 
>>> l2 =["red", "green", "black", "blue"]
>>> l3 = list()
>>> l3.append(l1)
>>> l3.append(l2)
>>> l3
[['apple', 'orange'], ['red', 'green', 'black', 'blue']]

use append() to append a list to your list 3

Or:

l3 = [l1, l2]

No matter which way you choose, the result:

>>> l3[0]
['apple', 'orange']
>>> l3[1]
['red', 'green', 'black', 'blue']

Upvotes: 2

Martin Forte
Martin Forte

Reputation: 873

If you have:

l1 = [1,2,3]
l2 = [4,5,6]

You can do:

l3 = list()
l3.append(l1)
l3.append(l2)

or:

l3 = [l1,l2]

Upvotes: 1

Matt C
Matt C

Reputation: 4555

You want to use the .append() method.

First, create a new array, then append the first list, then the second:

l3 = []
l3.append(l1)
l3.append(l2)

This gives you:

l3 = [["apple", "orange"], ["red", green", "black", "blue"]]

You can also do this shorter method:

l3 = [l1, l2]

Upvotes: 2

heemayl
heemayl

Reputation: 42127

Just do the following:

l3 = [l1, l2]

Upvotes: 3

TigerhawkT3
TigerhawkT3

Reputation: 49330

Just put the references in.

l3 = [l1, l2]

Note that, if you do this, modifying l1 or l2 will also produce the same changes in l3. If you don't want this to happen, use a copy:

l3 = [l1[:], l2[:]]

This will work for shallow lists. If they are nested, you're better off using deepcopy:

import copy
l3 = [copy.deepcopy(l1), copy.deepcopy(l2)]

Upvotes: 3

Related Questions