5

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

ayhan
  • 70,170
  • 20
  • 182
  • 203
Ravi Kumar
  • 1,769
  • 2
  • 21
  • 31

3 Answers3

5

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

tobspr
  • 8,200
  • 5
  • 33
  • 46
5

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
John1024
  • 109,961
  • 14
  • 137
  • 171
  • can we remove from the queue at desired position ? or we can only remove from ***popleft()*** ? – Madhi Jan 11 '18 at 16:00
  • Also note documentation [Indexed access is O(1) at both ends but slows to O(n) in the middle](https://docs.python.org/3/library/collections.html#collections.deque.maxlen) – Abhijit Sarkar Jul 11 '23 at 10:36
1

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
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119