5.1.1. Using Lists as Stacks

리스트를 스택처럼 사용하는 방법


The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index. For example:
리스트 메소드들(리스트 유형 안에 내장된 함수들)은 리스트를 스택처럼 사용하는 것을 무척 쉽게 만듭니다. '스택'이란 가장 나중에 추가된 요소가 가장 먼저 회수되는 것을 말합니다. ("last-in, first-out" 떡꼬치에 가장 마지막으로 끼운 떡을 제일 먼저 먹게 되는 것처럼...)
어떤 항목을 스택의 가장 위에 추가하기 위해서 .append( )를 사용합니다. 그리고 스택의 가장 위에 있는 항목을 불러오기 위해 .pop( )을 사용합니다. (.pop( )의 괄호 안에 특정 값을 집어넣지 않으면 가장 마지막 항목을 불러옵니다.)

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

results matching ""

    No results matching ""