0

im new to python i've just started. so im trying to merge two lists into each other in one big list. input:

A = [[a,1],[b,2],[c,3]]
B = [10,20,30]

desired output:

c = [[a,1,10],[b,2,20],[c,3,30]]

i tried insert method but it does not add B elements inside each individual list inside the A list and i tried c.extend([a,b]) but it gave me this:

[10,[a,1],20,[b,2],30,[c,3]]

what seems to be the problem because im really confused. thanks

wjandrea
  • 23,210
  • 7
  • 49
  • 68
Badei Ayasso
  • 23
  • 1
  • 4

3 Answers3

0

If you want c to be independent of a, you'll need to make a deep copy, either with the standard library copy.deepcopy or by hand-coding:

c = [ai[:] for ai in a]

and then extend each element list in c with the corresponding value from b:

for ci, bi in zip(c,b):
    ci.append(bi)

which does rely on the structure being exactly as you illustrate: each element of a is a list, and each element of b is a value.

If you just say c=a or c=a.copy() to start with, the lists inside a will also be affected by the append actions.

Joffan
  • 1,412
  • 1
  • 13
  • 18
0

One way to do this is to zip the input lists then add them:

a = [['a', 1], ['b', 2], ['c', 3]]
b = [10, 20, 30]

c = [x+[y] for x, y in zip(a, b)]
print(c)  # -> [['a', 1, 10], ['b', 2, 20], ['c', 3, 30]]
wjandrea
  • 23,210
  • 7
  • 49
  • 68
-2

if you always have a list of lists in the first variable, and a list of numbers, chars... in the second you could use this code :

a = [["a",1],["b",2],["c",3]]
b = [10,20,30]

def mergeLists(e,f):
    counter = 0
    for i in e:
        i.append(f[counter])
#add this line : 
mergeLists(a,b)

now if you print a you will get : a=[['a', 1, 10], ['b', 2, 10], ['c', 3, 10]] what this code do is iterating through the list e and adding every item of f, note that the lists must have the same length

note that you could do the same thing if you want to work just with a and b directly by using for i, j in zip(a, b): i.append(j)

oubaydos
  • 163
  • 1
  • 12
  • `counter` is never iterated. But actually, it'd be easier to use `zip` instead: `for i, j in zip(e, f): i.append(j)` – wjandrea May 20 '21 at 23:38