2

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?

0

5 Answers 5

3

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

1 Comment

If the downvoter or someone else would care to explain what is wrong with this answer, I would love to improve it.
3

Just do the following:

l3 = [l1, l2]

Comments

2

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]

Comments

2

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']

Comments

1

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]

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.