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?
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With