Skip to content

Commit 77ffa0d

Browse files
authored
Added pop.md (#7770)
* Added pop.md * minor content fix, error in codebyte fixed * Improve formatting in pop.md documentation Updated formatting for parameters, return value, and exceptions sections.
1 parent 53374fc commit 77ffa0d

File tree

1 file changed

+81
-0
lines changed
  • content/python/concepts/deque/terms/pop

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
---
2+
Title: '.pop()'
3+
Description: 'Removes and returns element from the right end of the deque.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Algorithms'
9+
- 'Collections'
10+
- 'Data Structures'
11+
- 'Deques'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/computer-science'
15+
---
16+
17+
The **`deque.pop()`** method removes and returns an element from the right end of a deque. Removing an element from either end of a deque occurs in O(1) time.
18+
19+
## Syntax
20+
21+
```pseudo
22+
deque.pop()
23+
```
24+
25+
**Parameters:**
26+
27+
This method does not take any parameters.
28+
29+
**Return value:**
30+
31+
Returns the element that was removed from the right end of the deque.
32+
33+
**Exceptions:**
34+
35+
- `IndexError`: Raised if the deque is empty when `.pop()` is called.
36+
37+
## Example
38+
39+
In this example, a single element is removed from the right end of the deque using `.pop()`:
40+
41+
```py
42+
from collections import deque
43+
44+
# Create a deque
45+
dq = deque([10, 20, 30, 40])
46+
47+
# Remove and return the rightmost element
48+
item = dq.pop()
49+
print("Removed element:", item)
50+
print("Deque after pop:", dq)
51+
```
52+
53+
This example results in the following output
54+
55+
```shell
56+
Removed element: 40
57+
Deque after pop: deque([10, 20, 30])
58+
```
59+
60+
## Codebyte Example: Popping the two rightmost elements
61+
62+
In this example, elements are removed from the right end of a deque one by one using `.pop()`:
63+
64+
```codebyte/python
65+
from collections import deque
66+
67+
# Create a deque with some numbers
68+
numbers = deque([1, 2, 3, 4, 5])
69+
70+
print("Initial deque:", numbers)
71+
72+
# Remove elements one by one from the right
73+
last_item = numbers.pop()
74+
print("Popped element:", last_item)
75+
print("Deque after first pop:", numbers)
76+
77+
# Pop again
78+
another_item = numbers.pop()
79+
print("Popped another element:", another_item)
80+
print("Final deque:", numbers)
81+
```

0 commit comments

Comments
 (0)