The popleft() method of deque class

The popleft() method removes an element from the left side of a Python deque instance. If the deque is empty, popleft() will raise an IndexError.

Deque Updated 20 Mar 2017 1 min read

Method signature

popleft()

Parameters

None

Return value

Returns the removed element.

Overview

  • A deque Python is double ended queue. Elements can be added and removed from either side of the deque.
  • The popleft() method removes an element from the left side of the deque and returns the element.
  • Invoking popleft() on an empty deque raises an exception of type IndexError.

Example

python
# Example Python program that removes an element

            # from a Python deque

            import collections

# Create a deque

            numberDeque = collections.deque((20, 40, 60, 80))

            print("Deque elements before invoking popleft():")

            print(numberDeque)

# Remove an element from the left of the deque

            element = numberDeque.popleft()

            print("The popleft() call removed the element:{}".format(element))

print("Deque elements after invoking popleft():")

            print(numberDeque)

Output

Output
Deque elements before invoking popleft():

            deque([20, 40, 60, 80])

            The popleft() call removed the element:20

            Deque elements after invoking popleft():

            deque([40, 60, 80])