I wish to know an efficient way and code saving to slice a list of thousand of elements
example:
b = ["a","b","c","d","e","f","g","h"]
index = [1,3,6,7]
I wish a result like as:
c = ["b","d","g","h"]
With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list. If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.
Python is a zero-indexed language (things start counting from zero), and is also left inclusive, right exclusive you are when specifying a range of values. This applies to objects like lists and Series , where the first element has a position (index) of 0.
Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.
The most direct way to do this with lists is to use a list comprehension:
c = [b[i] for i in index]
But, depending on exactly what your data looks like and what else you need to do with it, you could use numpy arrays - in which case:
c = b[index]
would do what you want, and would avoid the potential memory overhead for large slices - numpy arrays are stored more efficiently than lists, and slicing takes a view into the array rather than making a partial copy.
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