[PS] 스택(Stack)
Python1분 읽기
list를 스택으로 사용할 수 있다.
stack = []
# push
stack.append(1)
stack.append(2)
stack.append(3)
# stack = [1, 2, 3]
# pop
top = stack.pop()
# top = 3, stack = [1, 2]
# top
top = stack[-1]
# top = 2
# empty
if not stack:
print("스택이 비었습니다")
주의: 빈 배열일 때는 pop()을 할 수 없다.
# 잘못된 방식
stack = []
stack.pop() # IndexError: pop from empty list
# 옳은 방식
if stack:
stack.pop()
if len(stack) > 0:
stack.pop()
try:
stack.pop()
except IndexError:
pass