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]
Alexander McFarlane
  • 10,643
  • 9
  • 59
  • 100

3 Answers3

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]]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
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]]
Alexander McFarlane
  • 10,643
  • 9
  • 59
  • 100
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]]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218