w3resource

Python Exercise: Add more number of elements to a deque object from an iterable object

Python Collections: Exercise-9 with Solution

Write a Python program to add more number of elements to a deque object from an iterable object.

Sample Solution:

Python Code:

import collections
even_nums = (2, 4, 6, 8, 10)
even_deque = collections.deque(even_nums)
print("Even numbers:")
print(even_deque)
more_even_nums = (12, 14, 16, 18, 20)
even_deque.extend(more_even_nums)
print("More even numbers:")
print(even_deque)

Sample Output:

Even numbers:
deque([2, 4, 6, 8, 10])
More even numbers:
deque([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])

Flowchart:

Python Collections: Add more number of elements to a deque object from an iterable object.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to create a deque from an existing iterable object.
Next: Write a Python program to remove all the elements of a given deque object.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz


Python: Tips of the Day

Takes any number of iterable objects or objects with a length property and returns the longest one. If multiple objects have the same length, the first one will be returned

Example:

def tips_longest(*args):
  return max(args, key=len)

print(tips_longest('this', 'is', 'a', 'Python', 'Tutorial'))
print(tips_longest([1, 2, 3], [1, 2, 3, 4, 5], [1, 2]))
print(tips_longest([1, 2, 3], 'python'))

Output:

Tutorial
[1, 2, 3, 4, 5]
python