List and practice questions
.index()
We use this to find which position this value is in a list. It returns the FIRST occurrence index of that value.
for multiple indexes
But if you have multiple occurrences and want to find multiple indexes, you can’t use .index() because it will just return the first occurrence. Instead we should go through the entire list with enumerate and see the indexes of the values that we wanna find.
my_list = [1, 2, 3, 4, 5, 4, 3, 2, 1]
positions = [i for i, x in enumerate(my_list) if x == 4]
print(positions) # Output: [3, 5]
use dictionary for improvement
But finding index of a value in list through .index() or this way takes O(n) time, which is inefficient. A better way is to use dictionary when you are given a question that requires finding index of value often.
Use .get(key) method where .get(value) will give you the index. So the key of dictionary should be the value and value of dict should be the index(position)
If there are multiple occurrences, use enumerate again just like we did in a list.
Another alternative is to use binary search O(log n), but there is limitation of the list needs to be a sorted list so use it wisely