By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,282 Members | 1,314 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,282 IT Pros & Developers. It's quick & easy.

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

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?
Aug 10 '07 #1
Share this Question
Share on Google+
4 Replies

ilikepython
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.
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
Expert 100+
P: 844
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

P: 4
thanks guys, those are great solutions!
Aug 10 '07 #4

bvdet
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:
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.