For list we can get index of element list_name.index(3)
How to get index of item in deque.
ex:
d_list = deque([1, 2, 3, 4])
what is the best way to get the index of element 3.
Edit: I am using Python 2.7.6
For list we can get index of element list_name.index(3)
How to get index of item in deque.
ex:
d_list = deque([1, 2, 3, 4])
what is the best way to get the index of element 3.
Edit: I am using Python 2.7.6
Just use it like regular lists:
>>> d_list = collections.deque([1, 2, 3, 4])
>>> d_list.index(3)
2
Edit: This is only possible in Python 3.5 right now
According to the pythons docs, if you have python3.5 or better, you can use index
(as per tobspr's answer).
For older pythons, you can convert the deque to a list and then use index
:
In [5]: from collections import deque
In [6]: d_list = deque([1, 2, 3, 4])
In [7]: list(d_list).index(3)
Out[7]: 2
If you are using Python 2.x, deque
is not a good choice if you want to do lookup. You can either use list
or do the following using enumerate()
:
>>> def index(element, queue):
... for i, ele in enumerate(queue):
... if ele == element:
... return i
... raise ValueError("{} is not in queue".format(element))
>>> index(2, deque([1, 2, 3, 4]))
1
Alternatively, you can implement your own queue:
>>> class IndexedDeque(deque):
... def index(self, element):
... for i, ele in enumerate(self):
... if ele == element:
... return i
... raise ValueError("{} is not in queue".format(element))
>>> d_list = IndexedDeque([1, 2, 3, 4])
>>> d_list.index(2)
1