Function to retrieve index from Python (simple question)

Asked 2 years ago, Updated 2 years ago, 13 views

Question 1) For example, a=[2,3,4,3,2]a.index(2) will result in 0.
I know that the .index() function calls only one index that matches the first value in parentheses.
Is there a function that returns the value of all indexes that match the value in parentheses rather than 0? ([0,5] in this case)

Question 2) Assuming that Question 1 has been resolved, a.index(1) is a function to call an index with the same value as 1, but how do I code it to call an index with a value less than 1?
Of course, a.index(<1) won't work, so how should I make it?

python

2022-09-21 23:12

1 Answers

def indices(lst, n):
  return [ idx for idx, e in enumerate(lst) if e == n ]

def indices_condition(lst, cond):
  return [ idx for idx, e in enumerate(lst) if cond(e) ]

lst = [1,2,0,3,-1,0, 1]
indices_condition(lst, lambda e: e < 1)

It's possible in this way.


2022-09-21 23:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.