w3resource

Python: Create a deque from an existing iterable object

Python Collections: Exercise-8 with Solution

Write a Python program to create a deque from an existing iterable object.

Sample Solution:

Python Code:

import collections
even_nums = (2, 4, 6)
print("Original tuple:")
print(even_nums)
print(type(even_nums))
even_nums_deque = collections.deque(even_nums)
print("\nOriginal deque:")
print(even_nums_deque)
even_nums_deque.append(8)
even_nums_deque.append(10)
even_nums_deque.append(12)
even_nums_deque.appendleft(2)
print("New deque from an existing iterable object:")
print(even_nums_deque)
print(type(even_nums_deque))

Sample Output:

Original tuple:
(2, 4, 6)
<class 'tuple'>

Original deque:
deque([2, 4, 6])
New deque from an existing iterable object:
deque([2, 2, 4, 6, 8, 10, 12])
<class 'collections.deque'>

Flowchart:

Python Collections: Create a deque from an existing 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 and append few elements to the left and right, then remove some elements from the left, right sides and reverse the deque.
Next: Write a Python program to add more number of elements to a deque object from an iterable object.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz


Python: Tips of the Day

Curries a function.

Example:

from functools import partial

def tips_curry(fn, *args):
  return partial(fn,*args)
add = lambda x, y: x + y
add1 = tips_curry(add, 20)

print(add1(80))

Output:

100