Prepending to list python
Asked Answered
T

3

7

I have two lists:

a = [1,1,1]
b = [[2,2,2],[3,3,3]]

I want to prepend a on b in one line of code to create:

result = [[1,1,1],[2,2,2],[3,3,3]]

I want to also preserve a and b during the process so you cannot just do:

b[:0] = [a]
Torritorricelli answered 19/2, 2015 at 20:41 Comment(0)
B
14

Just use concatenation, but wrap a in another list first:

[a] + b

This produces a new output list without affecting a or b:

>>> a = [1,1,1]
>>> b = [[2,2,2],[3,3,3]]
>>> [a] + b
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
>>> a
[1, 1, 1]
>>> b
[[2, 2, 2], [3, 3, 3]]
Bergess answered 19/2, 2015 at 20:42 Comment(0)
T
3

solved

I actually took a swing in the dark and tried

result = [a]+b

which worked:

$ print [a]+b
$ [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
Torritorricelli answered 19/2, 2015 at 20:43 Comment(2)
I got excited by my new found knowledge and repeated it with [[0,0,0]]+[a]+b to ensure I wasn't just delirious with the simplicity of the solution. edited to match my QTorritorricelli
Glad you figured it out on your own too. :-)Bergess
Z
1

You can use the + operator to concatenate. Neither a nor b will be modified, as a new list will be created.

>>> [a] + b
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
Zollverein answered 19/2, 2015 at 20:42 Comment(3)
that is possibly the fastest reply I've every had! Thanks! solved it at the same time :)Torritorricelli
Actually @MartijnPeters beat me by 12 seconds, so technically his was the fastest reply you've ever had :)Zollverein
Sorry Cyber; you had the first upvote on the post though. :-)Bergess

© 2022 - 2024 — McMap. All rights reserved.