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,
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.
In : arr = numpy.array([1,23,4,6,7,8]) In : [(arr[i], arr[-i-1]) for i in range(len(arr) // 2)] Out: [(1, 8), (23, 7), (4, 6)]
Depending on the size of
arr, writing the entire thing in NumPy may be more performant:
In : arr = numpy.array([1,23,4,6,7,8]*100) In : %timeit [(arr[i], arr[-i-1]) for i in range(len(arr) // 2)] 10000 loops, best of 3: 167 us per loop In : %timeit numpy.vstack((arr, arr[::-1]))[:,:len(arr)//2] 100000 loops, best of 3: 16.4 us per loop
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 # first element (returns 1) a[-1] # last element (returns 3)