I am trying to dynamically get the first and last element from an array.
So, let us suppose the array has 6 elements.
test = [1,23,4,6,7,8]
If I am trying to get the first and last = 1,8
, 23,7
and 4,6
. Is there a way to get elements in this order? I looked at a couple of questions Link Link2. I took help of these links and I came up with this prototype..
#!/usr/bin/env python import numpy test = [1,23,4,6,7,8] test1 = numpy.array([1,23,4,6,7,8]) len_test = len(test) first_list = [0,1,2] len_first = len(first_list) second_list = [-1,-2,-3] len_second = len(second_list) for a in range(len_first): print numpy.array(test)[[first_list[a] , second_list[a]]] print test1[[first_list[a], second_list[a]]]
But this prototype won't scale for if you have more than 6 elements. So, I was wondering if there is way to dynamically get the pair of elements.
Thanks!
To get the first and last elements of an array, access the array at index 0 and the last index. For example, arr[0] returns the first element, whereas arr[arr. length - 1] returns the last element of the array.
You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
To get the last element of the list in Python, use the list[-1] syntax. The list[-n] syntax gets the nth-to-last element. So list[-1] gets the last element, and list[-2] gets the second to last. The list[-1] is the most preferable, shortest, and Pythonic way to get the last element.
I ended here, because I googled for "python first and last element of array", and found everything else but this. So here's the answer to the title question:
a = [1,2,3] a[0] # first element (returns 1) a[-1] # last element (returns 3)
How about:
In [10]: arr = numpy.array([1,23,4,6,7,8]) In [11]: [(arr[i], arr[-i-1]) for i in range(len(arr) // 2)] Out[11]: [(1, 8), (23, 7), (4, 6)]
Depending on the size of arr
, writing the entire thing in NumPy may be more performant:
In [41]: arr = numpy.array([1,23,4,6,7,8]*100) In [42]: %timeit [(arr[i], arr[-i-1]) for i in range(len(arr) // 2)] 10000 loops, best of 3: 167 us per loop In [43]: %timeit numpy.vstack((arr, arr[::-1]))[:,:len(arr)//2] 100000 loops, best of 3: 16.4 us per loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With