10

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"] 
1

1 Answer 1

17

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.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks lvc I have this error message c = b[index] Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: list indices must be integers, not list
@Gianni as I said in my answer, that will work if you use numpy arrays instead of lists. They can take all kinds of interesting things as indexes; lists can only take integers (and slices with integer arguments).
+1 for using a list comprehension. It's a good thing to teach newbies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.