Skip to content

Commit 76ee1eb

Browse files
authored
[Term Entry] Python deque: reverse()
* Add python reverse() method doc Add python reverse() method doc * minor updates * Minor changes ---------
1 parent 42b44a7 commit 76ee1eb

File tree

1 file changed

+70
-0
lines changed
  • content/python/concepts/deque/terms/reverse

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
---
2+
Title: '.reverse()'
3+
Description: 'Reverses the elements of a deque in-place.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Collections'
9+
- 'Deques'
10+
- 'Functions'
11+
- 'Methods'
12+
CatalogContent:
13+
- 'learn-python-3'
14+
- 'paths/computer-science'
15+
---
16+
17+
The **`.reverse()`** method of a Python [`collections.deque`](https://www.codecademy.com/resources/docs/python/collections-module/deque) reverses the order of elements in the deque in-place.
18+
19+
## Syntax
20+
21+
```pseudo
22+
deque.reverse()
23+
```
24+
25+
**Parameters:**
26+
27+
The `.reverse()` method doesn't take any parameters.
28+
29+
**Return value:**
30+
31+
The deque is modified in-place.
32+
33+
## Example
34+
35+
In this example, the elements of a deque are reversed in-place, changing the order of items:
36+
37+
```py
38+
from collections import deque
39+
40+
# Create a deque
41+
d = deque([1, 2, 3, 4])
42+
43+
# Reverse the order of deque's elements
44+
d.reverse()
45+
print(d)
46+
```
47+
48+
The output of this code is:
49+
50+
```shell
51+
deque([4, 3, 2, 1])
52+
```
53+
54+
## Codebyte Example
55+
56+
The following example reverses the deque in-place to flip the order of words in a sentence:
57+
58+
```codebyte/python
59+
from collections import deque
60+
61+
words = deque(["requests", "pull", "and", "calm", "keep"])
62+
print("Original deque:", list(words))
63+
print("Original sentence:", " ".join(words))
64+
65+
# Reverse the deque in-place to flip the sentence
66+
words.reverse()
67+
68+
print("After .reverse():", list(words))
69+
print("Reversed sentence:", " ".join(words))
70+
```

0 commit comments

Comments
 (0)