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]
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]
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]]
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]]
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]]
© 2022 - 2024 — McMap. All rights reserved.
[[0,0,0]]+[a]+b
to ensure I wasn't just delirious with the simplicity of the solution. edited to match my Q – Torritorricelli