Home > Blockchain >  Append values to a list that has a nested list python
Append values to a list that has a nested list python

Time:02-05

I have two lists:

L1 = [[a,b,c],[d,e,f]]
L2 = [1,2]

I want the output to be:

L3 = [[[a,b,c],1], [[d,e,f],2]]

How do I do this?

CodePudding user response:

You can also use a list comprehension, assuming your lists always have equal sizes:

L3 = [[L1[i], L2[i]] for i in range(len(L1))]
print(L3)

Output:

[[['a', 'b', 'c'], 1], [['d', 'e', 'f'], 2]]

CodePudding user response:

Try this with with zip operator

L1 = [['a','b','c'],['d','e',"f"]]
L2 = [1,2]
L3 = []
for (list1, list2) in zip(L1,L2):
    L3.append([list1, list2])
print(L3)

CodePudding user response:

The below seems to do the trick:

def combine(L1, L2):
    return [[e1, e2] for e1, e2 in zip(L1, L2)]

L1 = [['a', 'b', 'c'], ['d', 'e', 'f']]
L2 = [1,2]
L3 = combine(L1, L2)

Output:

[[['a','b','c'],1], [['d','e','f'],2]]

CodePudding user response:

You can use zip to create tuples and map each tuple into a list:

out = list(map(list, zip(L1,L2)))

Output:

[[['a', 'b', 'c'], 1], [['d', 'e', 'f'], 2]]

CodePudding user response:

from itertools import cycle

L1 = [['a','b','c'],['d','e','f']]
L2 = [1,2]

def do_something(L1,L2):
    combos = list(zip(L1,cycle(L2)))
    print(combos)
do_something(L1,L2)
  •  Tags:  
  • Related