-1

Let

a = [1, 2, ... 99, 100] # numbers 1 to 100
b = [2, 3, ... 89, 97] # prime numbers under 100

Is there a Pythonic way to slice a by b?

i.e.

a[b]

output would be

[3, 4, ... 90, 98]
Linsu Han
  • 135
  • 1
  • 8
  • 3
    Does this answer your question? [In Python, how do I index a list with another list?](https://stackoverflow.com/questions/1012185/in-python-how-do-i-index-a-list-with-another-list) – Sebastian Dziadzio Mar 12 '20 at 15:53

2 Answers2

2

How about:

result = [a[i] for i in b]
2

Since there is the numpy tag:

import numpy as np
a = np.array(a)
b = np.array(b)

result = a[b]

Time performance comparison:

import numpy as np
N=100_000

a = list(range(N))
b = list(range(1, N, 3))

c = np.array(a)
d = np.array(b)

List Comprehension

%timeit [a[i] for i in b]
2.31 ms ± 456 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Numpy

%timeit c[d]
115 µs ± 7.57 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Using a simple test we can see numpy is 20x faster with an array of lenght 100_000, however this is not a fair comparison, since I am not taking into account the time to import the library and convert lists to arrays.

As a final remark, there is actually no need to convert also b to a numpy array.

FBruzzesi
  • 6,385
  • 3
  • 15
  • 37