How can i merge 2 lists to form a new list

So i am just getting started and just going through the list section. The question is how can i merge multiple lists to create a new list.

I understanding using the zip function will give you a tuple. But i don’t want to create a tuple inside a list. I want to create a 2D list

anyone help?

Concatenation lets us combine two 1D lists into a single 1D list. This has the same effect of the list.extend() method.

Eg.

>>> lst = [1,2,3,4,5]
>>> lst.extend([6,7,8,9])
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst += [10, 11, 12, 13]
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
>>> 

To insert a list into a list we can use, list.append() to add it to the end; or, list.insert() to add it into the list at any index (must be specified).

>>> lst.append([14,15,16])
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, [14, 15, 16]]
>>> lst.insert(0, [-3, -2, -1, 0])
>>> lst
[[-3, -2, -1, 0], 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, [14, 15, 16]]
>>> 

Note that the two inserted lists are at one index position, each, lst[0] and lst[-1], respectively.

Thanks, @mtf for the reply. I am sorry i was a bit vague in my question

Here is my use case
lst1 = [1, 2, 3, 4, 5]
lst2 = [6, 7, 8, 9, 10]

i am trying to create a lst3 = [[1,6], [2, 7], [3, 8], [4, 9], [5, 10]]

Have you learned about list comprehensions, yet?

>>> lst1 = [1, 2, 3, 4, 5]
>>> lst2 = [6, 7, 8, 9, 10]
>>> [list(x) for x in zip(lst1, lst2)]
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
>>> 

If not, then we will have to look for another approach.


>>> lst1 = [1, 2, 3, 4, 5]
>>> lst2 = [6, 7, 8, 9, 10]
>>> lst3 = []
>>> for i, x in enumerate(lst1):
	lst3.append([x, lst2[i]])

	
>>> lst3
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
>>> 

Great this was what i was looking for. I haven’t reached list comprehensions yet. I just got to the while loop section. This will work for me. I see there is a list comprehension’s section a few lessons from where i am

Thanks so much

1 Like

Suggest don’t use the comprehension until you get to that lesson. Use the second method I posted in my edit.

Now, if you have not learned about the enumerate() function then we have to ease back to using a range.

>>> lst = []
>>> for i in range(len(lst1)):
	lst.append([lst1[i], lst2[i]])

	
>>> lst
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
>>> 
1 Like