Deque Operations in Python

Level 394 keystrokes

This demonstrates deque operations for adding elements at both ends.

Python code

# deque is a double-ended queue: fast adds and removals at both ends
1from collections import deque
2
# Starts with 1, 2, 3
3d = deque([1, 2, 3])
# appendleft() adds 0 at the front (a list would need insert(0, x), which is slow)
4d.appendleft(0)
# append() adds 4 at the end
5d.append(4)
# list() converts the deque so it prints as [0, 1, 2, 3, 4]
6print(list(d))

Output

[0, 1, 2, 3, 4]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 5
  • )× 5
  • ,× 2
  • .× 2
  • [× 1
  • ]× 1
  • =× 1

More Python examples at level 3

← Python typing practice