T = [L[i] for i in Idx]
Answer from van on Stack OverflowIn Python, how do I index a list with another list? - Stack Overflow
New to python, how can I get index of item in list?
Regarding list slicing: can anyone help me understand the reasoning behind inclusive vs. exclusive indexing with negative vs. non-negative integers?
list index out of range
The length is returning 3, the index is 0 - 2. Sometimes you randomly get 3 and the error message.
More on reddit.comVideos
I'm learning data structure and algorithms and i came across a question in the list section. i thought after i had understood python, i had understood list but a question was asked and i find myself finding it hard to understand how the list indexing works.
here's the sample code:
arr = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
arr[i - 1] = arr[i]
for i in range(0, 6):
print(arr[i], end = " ")
it looks simple to understand but, i just can't understand it.
T = [L[i] for i in Idx]
If you are using numpy, you can perform extended slicing like that:
>>> import numpy
>>> a=numpy.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
>>> Idx = [0, 3, 7]
>>> a[Idx]
array(['a', 'd', 'h'],
dtype='|S1')
...and is probably much faster (if performance is enough of a concern to to bother with the numpy import)