472,126 Members | 1,569 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,126 software developers and data experts.

inserting a list into a list (but not as a list)

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?
Aug 10 '07 #1
4 4843
ilikepython
844 Expert 512MB
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.
Expand|Select|Wrap|Line Numbers
  1. >>> x = [1, 2, 3]
  2. >>> y = [2, 4] + x + [5]
  3. >>> y
  4. [2, 4, 1, 2, 3, 5]
  5.  
Aug 10 '07 #2
ilikepython
844 Expert 512MB
You can try list concatenation.
Expand|Select|Wrap|Line Numbers
  1. >>> x = [1, 2, 3]
  2. >>> y = [2, 4] + x + [5]
  3. >>> y
  4. [2, 4, 1, 2, 3, 5]
  5.  
You can also use map:
Expand|Select|Wrap|Line Numbers
  1. >>> x = [1,  2, 3]
  2. >>> y = [2, 4]
  3. >>> map(y.append, x)
  4. >>> y
  5. [2, 4, 1, 2, 3]
  6.  
Aug 10 '07 #3
POINTS
4
thanks guys, those are great solutions!
Aug 10 '07 #4
bvdet
2,851 Expert Mod 2GB
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:
Expand|Select|Wrap|Line Numbers
  1. >>> x = [1,2,3]
  2. >>> y = [2,4,5]
  3. >>> [y.insert(i+2, item) for i,item in enumerate(x)]
  4. [None, None, None]
  5. >>> y
  6. [2, 4, 1, 2, 3, 5]
  7. >>> 
Aug 10 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

reply views Thread by Jonathan Moss | last post: by
3 posts views Thread by Joachim Klassen | last post: by
15 posts views Thread by John Salerno | last post: by
5 posts views Thread by dos360 | last post: by
reply views Thread by Edwin.Madari | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.