Monday, 14 January 2019

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...