Skip to main content
  1. About
  2. For Teams
Asked
Viewed 5k times
0

suppose we have:

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

What is the fastest way to access the array such that we get the first element in each list, other than looping.

i would like the result to be giving me... 1,4

0

4 Answers 4

2

using zip(*a)

a = [[1, 2, 3], [2, 3, 4]]
result = zip(*a)[0]
print result
Sign up to request clarification or add additional context in comments.

2 Comments

As a side note, this doesn't work in python3 as zip returns an iterable object... next(iter(zip(*a))) should work just about anywhere though.
list(zip(*a))[0] works in python2.7, and IMHO will also work in python3.0, because list() accepts an iterable and produces a list.
2

A quick and easy way is to just extract a[0][0] and a[1][0], but depending on what you are using it for, this might not work all the time.

Comments

2

Without looping, you need to unroll the loop as ethg242 does. This has the disadvantage of only working for a fixed length of a

Here is a list comprehension

[i[0] for i in a]

It's also possible to use map(), but this also has an implicit loop

from operator import itemgetter
map(itemgetter(0), a)

Comments

2

You might want to consider numpy:

>>> import numpy as np
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = np.array(a)
>>> b[:,0]
array([1, 4])

2 Comments

thanks you, but how do you convert this 2d array to a 1d array? I'm looking for a quick function haha :) much appreciated!
array([1,4]) is equivalent to [[1],[4]]

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.