-3

I am having two arrays:

X = [1,2,3,4,5]

and

Y = [10,20,30,40,50]

I am trying to combine two arrays into one where items from array X correspond to row=0 and items from array Y correspond to row=1.

So the new array looks like:

combined = [[1,10],[2,20],[3,30],[4,40],[5,50]]

I have tried the following methods:

for element in combined:
    for item in X:
        element[0] = item

This should add all elements from X into the first-row of combined Like that:

combined = [[1, 0],[2, 0],[3, 0],[4, 0],[5, 0]]

However, it does not work like I expected as it gives me the following result:

combined = [[1, 0],[1, 0],[1, 0],[1, 0],[1, 0]]
matheo-es
  • 33
  • 1
  • 5
  • 3
    try `list(zip(X,Y)) ` – Pygirl Dec 01 '20 at 17:18
  • 1
    Does this answer your question? [How to merge lists into a list of tuples?](https://stackoverflow.com/questions/2407398/how-to-merge-lists-into-a-list-of-tuples) – Pygirl Dec 01 '20 at 17:21
  • @Pygirl, It does partially the work. It returns [(1,10), (2,10)] instead of [[1,10], [2,10]]. So it returns the objects – matheo-es Dec 01 '20 at 17:31
  • [How to debug small programs.](//ericlippert.com/2014/03/05/how-to-debug-small-programs/) | [What is a debugger and how can it help me diagnose problems?](//stackoverflow.com/q/25385173/843953) You set the first index of `element` to _every element of `X`_. At the end of the inner for loop, the first index is set to the last element of `X`. This happens for all `element` in `combined`. You only need to set the corresponding element of `X` to the first index of `element` – Pranav Hosangadi Dec 01 '20 at 17:34
  • 1
    Then map them to a list by this :`list(map(list, zip(X, Y)))` – Pygirl Dec 01 '20 at 17:34

1 Answers1

-1

You can use zip to make that kind of combination:

X = [1,2,3,4,5]
Y = [10,20,30,40,50]

Z = [ list(p) for p in zip(X,Y) ]

print(Z) # [[1, 10], [2, 20], [3, 30], [4, 40], [5, 50]]
Alain T.
  • 40,517
  • 4
  • 31
  • 51