2

I am combining/merging two nested lists into one nested list.

list1 = [['T123', 'Tom', '1', 1], ['S222', 'Alice', '3', 2]]
list2 = [['T098', 'Jane', '2', 0], ['T432', 'Mandy', "5", 0]]
list_combine = []

list_combine.append(list1)
list_combine.append(list2)
print(list_combine)

The code gives the result of:

[[['T123', 'Tom', '1', 1], ['S222', 'Alice','3', 2]], [['T098', 'Jane', '2', 0], ['T432', 'Mandy', "5", 0]]]

Which looks like two nested list in another nested list. Not what I want. what I want is:

[['T123', 'Tom', '1', 1], ['S222', 'Alice','3', 2], ['T098', 'Jane', '2', 0], ['T432', 'Mandy', "5", 0]]

.append() doesn't seem to be the correct way. Any way can this be done? Thanks.

Keroberos
  • 41
  • 3

1 Answers1

1

You may use

list1 = [['T123', 'Tom', '1', 1], ['S222', 'Alice', '3', 2]]
list2 = [['T098', 'Jane', '2', 0], ['T432', 'Mandy', "5", 0]]
list_combine = [item for sublst in zip(list1, list2) for item in sublst]
print(list_combine)

Which yields

[['T123', 'Tom', '1', 1], ['T098', 'Jane', '2', 0], ['S222', 'Alice', '3', 2], ['T432', 'Mandy', '5', 0]]
Jan
  • 42,290
  • 8
  • 54
  • 79