{"id":25915,"date":"2021-12-03T21:29:18","date_gmt":"2021-12-03T15:59:18","guid":{"rendered":"https:\/\/python-programs.com\/?p=25915"},"modified":"2021-12-03T21:29:18","modified_gmt":"2021-12-03T15:59:18","slug":"python-collections-deque-method-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-collections-deque-method-with-examples\/","title":{"rendered":"Python collections Deque() Method with Examples"},"content":{"rendered":"

Deque:<\/strong><\/p>\n

In Python, the module “collections” is used to implement a Deque (Double Ended Queue). Deque is chosen over list when we need faster append and pop operations from both ends of the container, as deque has an O(1) time complexity for append and pop operations, whereas list has an O(n) time complexity.<\/p>\n

Access Operations on Deque():<\/strong><\/p>\n

append():<\/strong><\/p>\n

append() function adds the value in its argument to the right end of the \r\ndeque.<\/pre>\n

appendleft():<\/strong><\/p>\n

 appendleft() function inserts the value in its argument to the left end of\r\n the deque.<\/pre>\n

pop():<\/strong><\/p>\n

 pop() function is used to remove an argument from the deque's right end.<\/pre>\n

popleft():<\/strong><\/p>\n

 popleft() function is used to remove an argument from the deque's left end.<\/pre>\n

index(ele, beg, end):<\/strong><\/p>\n

 This method returns the first index of the value specified in parameters,\r\n beginning with beg and ending with end index.<\/pre>\n

insert(i, a):<\/strong><\/p>\n

Inserts the value specified in arguments(a) at the index(i) specified in\r\narguments.<\/pre>\n

remove():<\/strong><\/p>\n

This function deletes the first occurrence of the value specified in the \r\nparameters.<\/pre>\n

count():<\/strong><\/p>\n

This function counts the number of times the value specified in arguments \r\nappears.\r\n<\/pre>\n

extend(iterable):<\/strong><\/p>\n

This function adds several values to the right end of a deque. \r\nThe passed argument is iterable.\r\n<\/pre>\n

extendleft(iterable):<\/strong><\/p>\n

This function is used to add numerous values to the deque's left end. \r\nThe passed argument is iterable. As a result of left appends, the order is \r\nreversed.\r\n<\/pre>\n

reverse():<\/strong><\/p>\n

 This function reverses the order of deque elements.\r\n<\/pre>\n

rotate():<\/strong><\/p>\n

This function rotates the deque by the number of arguments supplied. \r\nIf the provided integer is negative, the rotation is to the left. Otherwise, \r\nrotate to the right.<\/pre>\n

collections Deque() Method with Examples in Python<\/h2>\n

1)append(), appendleft(), pop() ,popleft() Operations on deque<\/strong><\/p>\n

Approach:<\/strong><\/p>\n