deque()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Jun 5, 2024
Contribute to Docs

In Python, a deque is a double-ended queue that allows fast appends and pops from both ends. The deque() method, a part of the collections module, creates a new deque object.

Syntax

my_deque = deque(iterable, maxlen)
  • my_deque: The name of the deque object to be created.
  • iterable: The iterable to be used for intializing the deque.
  • maxlen: The maximum length for the deque.

Example

The following example demonstrates the usage of the deque method:

from collections import deque
fruit = 'apple'
fruit_slices = deque(fruit)
print(fruit_slices)

The above code produces the following output:

deque(['a', 'p', 'p', 'l', 'e'])

Here is another example using the deque method:

from collections import deque
friends = ['Dave', 'Mary', 'Luis', 'Zachary']
car_five_seater = deque(friends, 5)
print(car_five_seater)

The above code gives the following output:

deque(['Dave', 'Mary', 'Luis', 'Zachary'], maxlen=5)

Codebyte Example

The following codebyte example demonstrates the use of the deque method:

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy