Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepending to list python

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]
like image 399
Alexander McFarlane Avatar asked Feb 19 '15 20:02

Alexander McFarlane


1 Answers

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]]
like image 166
Martijn Pieters Avatar answered Oct 13 '22 07:10

Martijn Pieters