473,386 Members | 1,785 Online

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

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 4927
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
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