Merge two lists into a array

Hi,

I’m new to codeacdemy and I was hoping someone could help with the below:

I’m wandering if it’s possible to concatenate two lists in Python3 into a 2D list by index. For example:

List 1 = [1, 2, 3, 4]
List 2 = [A, B, C, D]

merge them to create:

[[A,1], [B,2], [C,3], [D,4]]

I appreciate I can just write it out like the above and assign to a variable, but is there a function that does this without having to write out the 2D list manually should you have two very large lists of equal length?

Thank you

The .zip() returns a zip object. If we cast this to list by using the list() function, we get an output which is similar to this:

a = [1,2,3]
b = [4,5,6]
print(list(zip(a,b))
#output: [(1,4),(2,5),(3,6)]

Converting to list here is necessary, as one can’t print a zip object. Now consider the output. It is almost what you want, with the exception that the nested iterables (the objects in parentheses ()) are not lists but tuples.
All you have to do now, is to convert these tuples to lists. The same list() function can be used.

Hint

Have you learnt list comprehensions yet? If you, consider how you would use those. If not, consider the following:
You want to change each tuple to a list. You already know you can use the list() function. Consider how you might change each tuple to a list. This process would involve the same process, repeated over and over…Remember, you have to loop through the list.

I hope this helps! My answers were designed as hints only here, but if you find yourself really stuck, feel free to ask for more help!

4 Likes

Thank you very much for this :slight_smile:

1 Like