P: 4

I am trying to insert a list into a list like this:
>>> x = [ 1, 2, 3]
>>> y = [ 2, 4, x , 5]
>>> y
[2, 4, [1, 2, 3], 5]
but what I really want is to have y = [2, 4, 1, 2, 3, 5]. What is the best way to do this?
 
Share this Question
Expert 100+
P: 844

I am trying to insert a list into a list like this:
>>> x = [ 1, 2, 3]
>>> y = [ 2, 4, x , 5]
>>> y
[2, 4, [1, 2, 3], 5]
but what I really want is to have y = [2, 4, 1, 2, 3, 5]. What is the best way to do this?
You can try list concatenation. 
>>> x = [1, 2, 3]

>>> y = [2, 4] + x + [5]

>>> y

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

  Expert 100+
P: 844

You can try list concatenation. 
>>> x = [1, 2, 3]

>>> y = [2, 4] + x + [5]

>>> y

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

You can also use map: 
>>> x = [1, 2, 3]

>>> y = [2, 4]

>>> map(y.append, x)

>>> y

[2, 4, 1, 2, 3]

 
P: 4

thanks guys, those are great solutions!
  Expert Mod 2.5K+
P: 2,851

I am trying to insert a list into a list like this:
>>> x = [ 1, 2, 3]
>>> y = [ 2, 4, x , 5]
>>> y
[2, 4, [1, 2, 3], 5]
but what I really want is to have y = [2, 4, 1, 2, 3, 5]. What is the best way to do this?
Here is one way:  >>> x = [1,2,3]

>>> y = [2,4,5]

>>> [y.insert(i+2, item) for i,item in enumerate(x)]

[None, None, None]

>>> y

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

>>>
    Question stats  viewed: 4758
 replies: 4
 date asked: Aug 10 '07
