Saturday, 2 July 2016

python - How to find all occurrences of an element in a list?



index() will just give the first occurrence of an item in a list. Is there a neat trick which returns all indices in a list?



Answer



You can use a list comprehension:



indices = [i for i, x in enumerate(my_list) if x == "whatever"]

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...