How to Implement Queue Using List in Python: Simple Guide
You can implement a queue in Python using a
list by adding elements with append() and removing them with pop(0) to follow the first-in, first-out order. This way, the first element added is the first one removed, mimicking queue behavior.Syntax
To use a list as a queue, you add items at the end with append() and remove items from the front with pop(0).
queue.append(item): Addsitemto the end of the queue.queue.pop(0): Removes and returns the first item in the queue.
python
queue = [] queue.append('first') # Add to queue queue.append('second') item = queue.pop(0) # Remove from queue print(item)
Output
first
Example
This example shows how to add three items to a queue and then remove them one by one, printing each removed item.
python
queue = [] # Add items to the queue queue.append('apple') queue.append('banana') queue.append('cherry') # Remove and print items in FIFO order while queue: item = queue.pop(0) print(item)
Output
apple
banana
cherry
Common Pitfalls
Using pop(0) on a list is simple but can be slow for large queues because it shifts all other elements. A common mistake is to use pop() without an index, which removes the last item, breaking the queue order.
Wrong way (removes last item):
queue = ['a', 'b', 'c'] item = queue.pop() # Removes 'c', not the first item
Right way (removes first item):
item = queue.pop(0) # Removes 'a', the first item
Quick Reference
Summary tips for using list as queue:
- Use
append()to add items at the end. - Use
pop(0)to remove items from the front. - For large queues, consider
collections.dequefor better performance.
Key Takeaways
Use list's append() to add items to the queue end.
Use pop(0) to remove items from the queue front, ensuring FIFO order.
pop(0) can be slow for large lists; consider deque for better performance.
Avoid using pop() without index as it removes the last item, not the first.
A list-based queue is simple but not optimal for heavy queue operations.