Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: create a list of lists

Tags:

python

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?

like image 264
hald Avatar asked Feb 27 '26 05:02

hald


1 Answers

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)]
like image 168
TigerhawkT3 Avatar answered Feb 28 '26 19:02

TigerhawkT3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!