乐闻世界logo
搜索文章和话题

How to check deque length in Python

1个答案

1

In Python, deque (double-ended queue) is a data structure provided by the deque class in the collections module, which supports fast insertion and deletion from both ends. If you want to check the length of a deque, you can use the built-in len() function, which is a simple and effective approach.

Below is a specific example demonstrating how to create a deque, add elements to it, and check its length:

python
from collections import deque # Create an empty deque d = deque() # Add elements to the deque d.append('a') d.append('b') d.appendleft('c') # Add an element to the left d.append('d') # Print the deque print("Current deque content:", list(d)) # Check the length of the deque length = len(d) print("Length of deque is:", length)

In this example, I first imported the deque class from the collections module and created a deque object named d. Then, I used the append() method to add two elements ('a' and 'b') to the right end of the deque, and the appendleft() method to add one element ('c') to the left. Finally, I added another element ('d') to the right end.

By calling len(d), we can obtain the current length of the deque, which outputs 4 here because the deque contains four elements.

This method is straightforward and ideal for quickly checking the length of a deque when needed.

2024年7月4日 10:34 回复

你的答案