Python #stack queue

Learning memo / memorandum

Stacks and queues

The last-in first-out (LIFO) type buffer is ** stack **, and the first-in first-out (FIFO) type buffer is ** queue **.

stack = []

for i in range(10):
    stack.append(i)
    if len(stack)>4:
        print(stack.pop())

Execution result

4 5 6 7 8 9

queue = []

for i in range(10):
    queue.append(i)
    if len(queue)>4:
        print(queue.pop(0))

Execution result

0 1 2 3 4 5

However, implementing a queue as a list is inefficient because after the first data is retrieved by pop (0), the rest of the data must be shifted one by one, so use the deque in the collections package. Use.

from collections import deque

queue = deque([])

for i in range(10):
    queue.append(i)
    if len(queue)>4:
        print(queue.popleft())

Execution result

0 1 2 3 4 5

Recommended Posts

Python #stack queue
Stack and Queue in Python
Queue processing in Python
Python
Algorithm learned with Python 18th: Sorting (stack and queue)
queue
[Python Queue] Convenient use of Deque
View stack trace using [Python] inspect
I wrote the queue in Python
Show stack trace with python exception
Depth-first search using stack in Python
I wrote the stack in Python
kafka python
Python Summary
Built-in python
Python comprehension
Python technique
Ant book in python: Priority queue self-implementation
Studying python
Python 2.7 Countdown
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
Python memo
ufo-> python (3)
Python comprehension
install python
Python basics ④
Python Memorandum 2
python memo
Implementation module "deque" in queue and Python
Python Jinja2
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Python memo
Python iterative
Python algorithm
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
Start python
[Python] Sort
Note: Python
Python basics ③
python log
Python basics
[Scraping] Python scraping
Python update (2.6-> 2.7)
python memo
Python memorandum