|
| 1 | +--- |
| 2 | +Title: 'extend()' |
| 3 | +Description: 'Adds multiple elements to the right end of a deque from any iterable.' |
| 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 **`extend()`** method adds multiple elements to the right end of a `deque` from any iterable (like a [list](https://www.codecademy.com/resources/docs/python/lists), [tuple](https://www.codecademy.com/resources/docs/python/tuples), or another deque). It modifies the deque in place and returns `None`. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +```pseudo |
| 22 | +deque.extend(iterable) |
| 23 | +``` |
| 24 | + |
| 25 | +**Parameters:** |
| 26 | + |
| 27 | +- `iterable`: A sequence or iterable whose elements will be added to the right end of the deque. |
| 28 | + |
| 29 | +**Return value:** |
| 30 | + |
| 31 | +This method does not return any value. It modifies the deque in-place. |
| 32 | + |
| 33 | +## Example |
| 34 | + |
| 35 | +In this example, `extend()` adds elements from a list and another deque to the right end of a deque: |
| 36 | + |
| 37 | +```py |
| 38 | +from collections import deque |
| 39 | + |
| 40 | +# Create a deque |
| 41 | +dq = deque([1, 2, 3]) |
| 42 | + |
| 43 | +# Extend it |
| 44 | +dq.extend([4, 5, 6]) |
| 45 | +print("Extending with list: ", dq) |
| 46 | + |
| 47 | +#Extend it using another deque |
| 48 | +dq.extend(deque([7, 8, 9])) |
| 49 | +print("Extending with another deque: ", dq) |
| 50 | +``` |
| 51 | + |
| 52 | +This example results in the following output: |
| 53 | + |
| 54 | +```shell |
| 55 | +Extending with list: deque([1, 2, 3, 4, 5, 6]) |
| 56 | +Extending with another deque: deque([1, 2, 3, 4, 5, 6, 7, 8, 9]) |
| 57 | +``` |
| 58 | + |
| 59 | +## Codebyte Example: Extending a deque with a list and a tuple |
| 60 | + |
| 61 | +In this example, `extend()` adds elements from a list and a tuple, demonstrating its ability to handle different iterables: |
| 62 | + |
| 63 | +```codebyte/python |
| 64 | +from collections import deque |
| 65 | +
|
| 66 | +# Create a deque with some initial elements |
| 67 | +fruits = deque(["apple","banana"]) |
| 68 | +
|
| 69 | +print("Initital deque:", fruits) |
| 70 | +
|
| 71 | +# Add multiple elements to the right using extend() |
| 72 | +fruits.extend(["cherry", "date", "elderberry"]) |
| 73 | +
|
| 74 | +# Extend again using a tuple |
| 75 | +fruits.extend(("fig", "grape")) |
| 76 | +print("Deque after extending with a tuple:", fruits) |
| 77 | +``` |
0 commit comments