본문 바로가기

Python/모듈

파이썬에서 큐(queue) 사용하기(deque 사용법)

deque

`deque`는 `list`객체와 유사하지만 `list`는 데이터 크기가 고정되어 있을 때 최적화 되어 있어서, 하부 데이터를 변경하는 `pop(0)`과 `insert(0, v)`연산을 하는데 많은 비용(`O(n)`)이 소모됩니다. 이에 반해 `deque`는 객체의 양쪽 끝 에서의 추가(append)와 팝(pop)을 낮은 비용(`O(1)`)으로 지원하는 객체입니다.

선언

`deque`는 `collections`모듈의 하위 객체입니다.

from collections import deque


`deque`는 다음과 같이 생성할 수 있습니다.

deque(데이터, 최대 길이)


데이터가 비어있는 경우 비어있는 `deque`를 반환합니다.

최대 길이 인자를 이용해 `deque`의 최대 길이를 제한할 수 있으며, 지정하지 않을 경우 임의로 커질
수 있습니다.

사용 방법

appendleft()

`list`의 `append`와 비슷하게 이용하며, 추가되는 위치는 객체의 처음(왼쪽)입니다. `list`에서 `insert(0, v)`와 같은 동작을 합니다.

popleft()

객채의 가장 처음(왼쪽)에 있는 요소를 제거하고 그 요소를 반환합니다. `list`의 `pop(0)`과 같은 동작을 합니다.

참고

https://docs.python.org/ko/3/library/collections.html#collections.deque

collections — Container datatypes

Source code: Lib/collections/__init__.py This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.,,...

docs.python.org