Index-finding function... (Clean up questions)

Asked 2 years ago, Updated 2 years ago, 31 views

This was what I wanted.

When list = [1,2,3,4] is present

Given A = [3,2]

I was wondering if there is a code that makes it easier to get Answer with the following code. The code below seems to consume a lot of calculation speed because the list length is large because it uses a for statement.

Answer = []


for i in range(0,len(list)):

    if list[i] in A:

        Answer.append(i)

python

2022-09-21 11:39

2 Answers

What does "at once" mean?

Do you mean a line of code?

Or are you going to search each list only once?

Assuming that the length of the list is n and the length of a is m, assuming the worst situation in both cases

When using a for statement, the number of elements searched is n * m,

When using index, the number of elements searched is m * n.

I don't think there will be a big difference in execution time.

If you use the for statement, you can find duplicate values instead of taking more time because you keep searching even if you find the right answer, and the index stops searching if you find the right answer, so instead of taking a little less time, you move on without looking for duplicate values.

If you just wanted a code that runs in one line, try it as below.

>>> list = [1, 2, 3, 4]
>>> a = [3, 2]
>>> list(map(lambda x: list.index(x), a))
[2, 1]

However, I think it would be good to think about how this is different from when you execute the for statement.


2022-09-21 11:39

However, the Delete button disappears for questions that have already been answered. (Comments don't matter)


2022-09-21 11:39

If you have any answers or tips


© 2025 OneMinuteCode. All rights reserved.