파이썬에서 리스트의 길이를 일정하게 유지하는 예시(오래된 원소 제거)

파이썬에서 리스트에 원소를 추가하면서 일정 길이를 넘지 않도록 가장 오래된 원소를 제거하는 예시입니다. 리스트 길이, 즉 원소의 수가 3을 넘지 않도록 하면서 원소를 추가하는 함수를 아래와 같이 만들어 볼 수 있습니다.

MY_LIST = []
MAX_LEN = 3

def add_item(item):
  global MY_LIST
  if len(MY_LIST) == MAX_LEN:
    MY_LIST.pop(0)
  MY_LIST.append(item)

변수 MY_LIST의 길이가 3이 되면 인덱스 0의 원소를 제거하고, 새로 추가할 원소를 append() 함수를 이용해서 가장 마지막 인덱스에 추가되도록 합니다.

아래와 같이 수자 0~4를 차례로 추가하는 경우를 보면, 길이를 3 이하로 유지하기 때문에 처음에 추가했던 0과 1을 제거되고 MY_LIST는 [2, 3, 4] 이렇게 됩니다.

for i in range(5):
  add_item(i)

print(MY_LIST)

@joviansummer의 스팀 프로젝트

스팀 증인노드를 운영중입니다. @jswit에 증인투표해 주시면 감사하겠습니다.
(https://steemitwallet.com/~witnesses)

jswit 증인 노드 프로젝트를 시작합니다.

jsup 업보팅(upvoting) 서비스 소개

jsup 수혜자 지정 기능 추가

jSTEEM 프로젝트 - 텔레그램 챗봇으로 구현하는 스팀 블럭체인 탐색기

STEEM.NFT - 디지털 아트 보존 프로젝트

Posted through the AVLE Dapp (https://avle.io)

Sort:  

Thank you, friend!
I'm @steem.history, who is steem witness.
Thank you for witnessvoting for me.
image.png
please click it!
image.png
(Go to https://steemit.com/~witnesses and type fbslo at the bottom of the page)

The weight is reduced because of the lack of Voting Power. If you vote for me as a witness, you can get my little vote.

Upvoted! Thank you for supporting witness @jswit.

Hello, friend!

This post has been upvoted by the Steemgoon curation team.

Thank you for sharing content and contributing to the STEEM blockchain.


Please support us @steemgoon.witnez as one of your witness votes, you will get daily steem rewards and upvoted.

Coin Marketplace

STEEM 0.13
TRX 0.33
JST 0.034
BTC 112037.89
ETH 4314.86
SBD 0.85