469,641 Members | 1,334 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,641 developers. It's quick & easy.

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 4806
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
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.