Roshin Raphel
Roshin Raphel

Reputation: 2699

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 array like :

a = [[1,2],[3,4],[5,6]]
list(pd.DataFrame(a)[0])

or

a = [[1,2],[3,4],[5,6]]
list(np.array(a)[:,0])

which both yields [1,3,5].

Upvotes: 1

Views: 1373

Answers (5)

Nikhil kumar
Nikhil kumar

Reputation: 11

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])

Upvotes: -1

yatu
yatu

Reputation: 88236

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.

Upvotes: 2

Manoj Kumar Dhakad
Manoj Kumar Dhakad

Reputation: 1892

You can try map function.

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

Upvotes: 1

Sowjanya R Bhat
Sowjanya R Bhat

Reputation: 1168

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.

Upvotes: 0

Alexander Lekontsev
Alexander Lekontsev

Reputation: 1012

Like this

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

Upvotes: 2

Related Questions