0

hey what I need to do is that I have the lists below:

g=[[1,2,3],[4,5,6],[7,8,9]]
h=[[10,11,12,13],[14,15,16,17]]

and I need to get add the first index from list h into the list g. the results should be like list below:

g=[[1,2,3,10,14],[4,5,6,11,15],[7,8,9,12,16]]

and this what I have done so far but it's not working:

g=[[1,2,3],[4,5,6],[7,8,9]]
h=[[10,11,12,13],[14,15,16,17]]
for i in range(len(g)):
   for u in range(len(g[0])):
      g[i].append(h[i][u])

4 Answers 4

1
g=[[1,2,3],[4,5,6],[7,8,9]]
h=[[10,11,12,13],[14,15,16,17]]

idx = 0
for L1 in g:
    for L2 in h:
        L1.append(L2[idx])
    idx+=1

g

Returns

[[1, 2, 3, 10, 14], [4, 5, 6, 11, 15], [7, 8, 9, 12, 16]]

Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

Better use enumerate, that's what it's for.
0

If you use enumerate() and list comprehension, you can do a faster one-liner:

g = [n + [m[i] for m in h] for i, n in enumerate(g)]
# Returns: [[1, 2, 3, 10, 14], [4, 5, 6, 11, 15], [7, 8, 9, 12, 16]]

Comments

0

another way:

making a zip object hz from h contents (*h), next(hz) auto increments as the list comprehension walks through g
[*next(hz)] (or list(next(hz))) converts the tuple from the zip object into a list

g =[[1,2,3],[4,5,6],[7,8,9]]
h=[[10,11,12,13],[14,15,16,17]]

hz = zip(*h)
g = [e + [*next(hz)] for e in g]

g
Out[133]: [[1, 2, 3, 10, 14], [4, 5, 6, 11, 15], [7, 8, 9, 12, 16]]  

and for some the goal is a 'one-liner':

g = [e + list(f) for e, f in zip(g, zip(*h))]

Comments

0

I'd make the outer loop over h instead of g. No indexes needed.

>>> g = [[1,2,3],[4,5,6],[7,8,9]]
>>> h = [[10,11,12,13],[14,15,16,17]]
>>> for hlist in h:
        for glist, hvalue in zip(g, hlist):
            glist.append(hvalue)

>>> g
[[1, 2, 3, 10, 14], [4, 5, 6, 11, 15], [7, 8, 9, 12, 16]]

In other words: Instead of taking each g-list and fetching additional values from the h-lists, take each h-list and spread its values over the g-lists.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.