The Python Deque module USES elaboration

  • 2020-04-02 13:48:26
  • OfStack

Create the Deque sequence:


from collections import deque

d = deque()

Deque provides a list-like operation method:


  d = deque()
  d.append('1')
  d.append('2')
  d.append('3')
  len(d)
  d[0]
  d[-1]

Output results:


  3
  '1'
  '3'

Use pop on both ends:


  d = deque('12345')
  len(d)
  d.popleft()
  d.pop()
  d

Output results:


  5
  '1'
  '5'
  deque(['2', '3', '4'])

We can also limit the length of the deque:

      D = deque (maxlen = 30)

When the length limited deque increases the number of items exceeding the limit, the items on the other side are automatically deleted:


  d = deque(maxlen=2)
  d.append(1)
  d.append(2)
  d
  d.append(3)
  d
  deque([1, 2], maxlen=2)
  deque([2, 3], maxlen=2)

Add items in the list to deque:


  d = deque([1,2,3,4,5])
  d.extendleft([0])
  d.extend([6,7,8])
  d

Output results:


  deque([0, 1, 2, 3, 4, 5, 6, 7, 8])


Related articles: