schtopps
schtopps

Reputation: 2847

How to get first AND last element of tuple at the same time

I need to get the first and last dimension of an numpy.ndarray of arbitrary size.

If I have shape(A) = (3,4,4,4,4,4,4,3) my first Idea would be to do result = shape(A)[0,-1] but that doesn't seem to work with tuples, why not ??

Is there a neater way of doing this than

s=shape(A)
result=(s[0], s[-1])

Thanks for any help

Upvotes: 12

Views: 39885

Answers (4)

user7548672
user7548672

Reputation:

Came across this late; however, just to add a non indexed approach as previously mentioned.

Tuple unpacking can be easily be applied to acquire the first and last elements. Note: The below code is utilizing the special asterisk '*' syntax which returns a list of the middle section, having a and c storing the first and last values.

Ex.

A= (3,4,4,4,4,4,4,3)
a, *b, c = A
print((a, c))

Output (3, 3)

Upvotes: 6

unsym
unsym

Reputation: 2200

If you are using numpy array, then you may do that

s = numpy.array([3,4,4,4,4,4,4,3])
result = s[[0,-1]]

where [0,-1] is the index of the first and last element. It also allow more complex extraction such as s[2:4]

Upvotes: 2

kev
kev

Reputation: 161644

s = (3,4,4,4,4,4,4,3)
result = s[0], s[-1]

Upvotes: 6

Sven Marnach
Sven Marnach

Reputation: 601529

I don't know what's wrong about

(s[0], s[-1])

A different option is to use operator.itemgetter():

from operator import itemgetter
itemgetter(0, -1)(s)

I don't think this is any better, though. (It might be slightly faster if you don't count the time needed to instantiate the itemgetter instance, which can be reused if this operation is needed often.)

Upvotes: 26

Related Questions