Vural Erdogan
Vural Erdogan

Reputation: 111

Extract first column of a 2D list along with indices in a single line

How would you short these two list comprehension to one line? I would like to code as one line. My way seems too long. I feel like there is another way to code it.

y = [array[i][0] for i in range(len(array))]
x = [i for i in range(len(array))]

x, y = [i for i in range(len(array))], [array[i][0] for i in range(len(array))]

Upvotes: 0

Views: 2270

Answers (3)

cs95
cs95

Reputation: 402423

Assuming you want to extract the first column of a 2D list along with it's indices, you'd use enumerate with inverse-zip unpacking:

array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x, y = zip(*enumerate([r[0] for r in array]))

print(x)
(0, 1, 2)

print(y)
(1, 4, 7)

x is the index, and y is the row vector. As seen above, this method results in your data being extracted out as tuples (not lists), and will fail when array is empty.

So, as @user2357112 said in their comment, please don't endeavour to shove all your code into one line – do it only when it can be done and makes sense to do so.

Furthermore, to extend the discussion in comments, the best way to do this would be to follow a 2-step approach as shown by @Rakesh in their answer:

x = list(range(len(array)))
y = [r[0] for r in array]

print(x)
[0, 1, 2]

print(y)
[1, 4, 7]

This doesn't suffer from the drawbacks mentioned above.

Upvotes: 6

ely
ely

Reputation: 77414

x, y = list(map(list, zip(*[(i, r[0]) for i, r in enumerate(a)]))) or ([], [])

disclaimer: I think it's a situation where one-liner-ness is a bad thing.

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

This should help

x = range(len(array))    #range returns  list
y = [i[0] for i in array]    #you can access the element in the list without range or len 

Upvotes: 2

Related Questions