Fix Python – What is the syntax to insert one list into another list in python?

Question

Asked By – Soumya

Given two lists:

x = [1,2,3]
y = [4,5,6]

What is the syntax to:

  1. Insert x into y such that y now looks like [1, 2, 3, [4, 5, 6]]?
  2. Insert all the items of x into y such that y now looks like [1, 2, 3, 4, 5, 6]?

Now we will see solution for issue: What is the syntax to insert one list into another list in python?


Answer

Do you mean append?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]

Or merge?

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6] 

This question is answered By – Paolo Bergantino

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0