1

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

3
  • 2
    zip them together and concat: [l+[n] for l, n in zip(a, b)] Commented May 20, 2021 at 23:27
  • Welcome to Stack Overflow! Please take the tour and read How to Ask. What did you try exactly? I'm really not sure how you got that output. Also, are the variables a, b, c meant to be strings? If so they should be in quotes. Commented May 20, 2021 at 23:32
  • C = [ A[i] + [B[i]] for i in range(len(A))] Commented May 20, 2021 at 23:40

2 Answers 2

3

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.