Take only one side of a list of lists and add to a new list

Question:

Say I have multiple lists of lists. Something like this:

list1 = [[1,2],[56,32],[34,244]]
list2 = [[43,21],[30,1],[19,3]]
list3 = [[1,3],[8,21],[9,57]]

I want to create two new lists:

right_side = [2,32,244,21,1,3,3,21,57]
left_side = [1,56,34,43,30,19,1,8,9]

All sub-lists have only two values. And all big lists (list1,list2,list3) have the same number of values as well.

How do I do that?

Asked By: Programming Noob

||

Answers:

By using zip built-in function you get tuples:

left_side, right_side = zip(*list1, *list2, *list3)

And if you really need lists:

left_side, right_side = map(list, zip(*list1, *list2, *list3))
Answered By: Jonathan Dauwe

The below seems to work.

list1 = [[1, 2], [56, 32], [34, 244]]
list2 = [[43, 21], [30, 1], [19, 3]]
list3 = [[1, 3], [8, 21], [9, 57]]

left = []
right = []
lst = [list1, list2, list3]
for l in lst:
    for ll in l:
        left.append(ll[0])
        right.append(ll[1])
print(f'Left: {left}')
print(f'Right: {right}')
Answered By: balderman

If you do not have any issues with importing some standard libraries, you might achieve the goal as follows:

import itertools
from operator import itemgetter

right_side = list(map(itemgetter(1), itertools.chain(list1, list2, list3)))
left_side = list(map(itemgetter(0), itertools.chain(list1, list2, list3)))

Output of the due prints shall be:

[2, 32, 244, 21, 1, 3, 3, 21, 57]
[1, 56, 34, 43, 30, 19, 1, 8, 9]
Answered By: alphamu

You can use numpy

import numpy as np
All =  list1+list2+list3
All = np.array(All)
print(All[:,1].tolist())

Gives right elemnst #

[2, 32, 244, 21, 1, 3, 3, 21, 57]

To get left #

print(All[:,0].tolist())

Gives #

[1, 56, 34, 43, 30, 19, 1, 8, 9]
>>> 
Answered By: Bhargav
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.