Skip to content Skip to sidebar Skip to footer

Extract Elements In A Nested List Into Separate Lists According To The Positions

I have a nested list say : [[1,2], [3,4], [5,6]] How can I extract a column from this list, (either [1,3,5] or [2,4,6]) without converting it into a pandas DataFrame or an np ar

Solution 1:

Like this

col = 0
[item[col] for item in a]

Solution 2:

Use zip to unpack you lists as:

a = [[1,2],[3,4],[5,6]]

list1, list2 = zip(*a)

zip returns an iterator of tuples, which are then unpacked into list1 and list2, if you want lists, map to list and then unpack:

list1, list2 = map(list,zip(*a))
print(list1)
[1, 3, 5]
print(list2)
[2, 4, 6]

zip aggrates the elements from the input iterables. By unpacking with zip(*a), we're making each inner list a separate iterable in in zip, which will then "combine" the elements in each of these according to their positions.


Solution 3:

You can try map function.

y=list(map(lambda x:x[0],a))

Solution 4:

This might help if you want one-line list comprehension:

a = [[1,2],[3,4],[5,6]]

print([[elem[i] for elem in a] for i in range(len(a[0]))])

NOTE: len(a[0]) is what I'm using , so this will work only for inner-lists of equal lengths.


Solution 5:

I am a beginner in python, could you please try this.

a = [[1,2],[3,4],[5,6]]
for i in a:
    print(i[0])

Post a Comment for "Extract Elements In A Nested List Into Separate Lists According To The Positions"