riku_zac
riku_zac

Reputation: 55

how do i append two nested list into single nested list in python

i have two nested list like:

a = [[2,3,4],[3,5,6]]
b = [[4,5], [5,6,7,7,7]]

i need to append two nested list into single nested list.

Expected output:

[[4, 5], [5, 6, 7, 7, 7], [2, 3, 4], [3, 5, 6]]

I tried this way,

a = [[2,3,4],[3,5,6]]
b = [[4,5], [5,6,7,7,7]]
b.append(a)
print(b)

output i got:

[[4, 5], [5, 6, 7, 7, 7], [[2, 3, 4], [3, 5, 6]]]

Any suggestions would be helpful!

Upvotes: 2

Views: 617

Answers (3)

zipa
zipa

Reputation: 27869

Unpacking is one way of doing it:

c = [*a, *b]
# [[2, 3, 4], [3, 5, 6], [4, 5], [5, 6, 7, 7, 7]]

Upvotes: 2

PKumar
PKumar

Reputation: 11128

Use .extend, given

a = [[2,3,4],[3,5,6]]
b = [[4,5], [5,6,7,7,7]]
b.extend(a)

Note: the .extend method extends the existing list and changes made are in the list on which .extend is performed, so here changes are made to b

output:

[[4, 5], [5, 6, 7, 7, 7], [2, 3, 4], [3, 5, 6]]

Upvotes: 1

sloppypasta
sloppypasta

Reputation: 1126

Just create a new list:

a = [[2,3,4],[3,5,6]]
b = [[4,5], [5,6,7,7,7]]
c = a + b
# [[2, 3, 4], [3, 5, 6], [4, 5], [5, 6, 7, 7, 7]]

Upvotes: 2

Related Questions