[Python][자료구조] 리스트 : 아이템 추가, 삭제

·2023년 3월 19일
0
post-thumbnail

✒️ 리스트 아이템 추가하기

📌append() 함수

append() 함수를 이용하면 마지막 인덱스에 아이템을 추가할 수 있다.

sports = ['농구', '축구', '수구', '마라톤', '테니스']
print(f'list의 길이 : {len(sports)}')
print(f'list의 마지막 인덱스 : {len(sports) - 1}')
sports.append('골프')
print('-' * 30)
print(f'list의 길이 : {len(sports)}')
print(f'list의 마지막 인덱스 : {len(sports) - 1}')

💡result
list의 길이 : 5
list의 마지막 인덱스 : 4
------------------------------
list의 길이 : 6
list의 마지막 인덱스 : 5


scores = [['수학', 70],
          ['영어', 80],
          ['국어', 70],
          ['과학', 50]]

print(scores)
scores.append(['코딩', 100])
print(scores)

💡result

[['수학', 70], ['영어', 80], ['국어', 70], ['과학', 50]]
[['수학', 70], ['영어', 80], ['국어', 70], ['과학', 50], ['코딩', 100]]

📌insert() 함수

insert() 함수를 이용하면 특정위치(인덱스)에 아이템을 추가할 수 있다.

  • insert (추가할 아이템 인덱스, 아이템)
sports = ['농구', '축구', '수구', '마라톤', '테니스']
print(f'아이템 추가 전 : {sports}')
sports.insert(3, '골프') # 3번째 인덱스에 아이템 추가
print(f'아이템 추가 후 : {sports}')

💡result

아이템 추가 전 : ['농구', '축구', '수구', '마라톤', '테니스']
아이템 추가 후 : ['농구', '축구', '수구', '골프', '마라톤', '테니스']

✍️실습

오름차순으로 정렬되어 있는 숫자들에 사용자가 입력한 정수를 추가하는 프로그램 (단, 추가 후에도 오름차순 정렬 유지)

numbers = [1, 3, 6, 11, 45, 54, 62, 74, 85]
inputNumber = int(input('추가할 숫자 입력 : '))

for idx, value in enumerate(numbers):
    if inputNumber < value:
        numbers.insert(idx, inputNumber)
        break
    else:
        if idx == len(numbers) - 1:
            numbers.append(inputNumber)
            break

print(numbers)


💡result

추가할 숫자 입력 : 90
[1, 3, 6, 11, 45, 54, 62, 74, 85, 90]

추가할 숫자 입력 : 22
[1, 3, 6, 11, 22, 45, 54, 62, 74, 85]

✒️ 리스트 아이템 삭제하기

📌pop() 함수

pop() 함수를 이용하면 마지막 인덱스에 해당하는 아이템을 삭제할 수 있다.


sports = ['농구', '축구', '수구', '골프', '마라톤', '테니스']
print(sports)
print(f'sports 길이 :{len(sports)}')
print('-' * 30)
val = sports.pop()
print(f'sports.pop() --> {val} 삭제')
print(sports)
print(f'sports 길이 :{len(sports)}')
print('-' * 30)
val = sports.pop(3)
print(f'sports.pop(3) --> {val} 삭제')
print(sports)
print(f'sports 길이 :{len(sports)}')
print('-' * 30)


💡result

['농구', '축구', '수구', '골프', '마라톤', '테니스']
sports 길이 :6
------------------------------
sports.pop() --> 테니스 삭제
['농구', '축구', '수구', '골프', '마라톤']
sports 길이 :5
------------------------------
sports.pop(3) --> 골프 삭제
['농구', '축구', '수구', '마라톤']
sports 길이 :4
------------------------------

✍️실습

최고, 최저 점수 구하기

scores = [9.5, 8.5, 9.0, 7.5, 6.5, 8]

max = scores[0]
min = scores[0]
maxIdx = 0
minIdx = 0
scoresCopy = scores.copy()

for idx, score in enumerate(scores):
    if max < score:
        max = score
        maxIdx = idx

scores.pop(minIdx)

for idx, score in enumerate(scoresCopy):
    if min > score:
        min = score
        minIdx = idx
scores.pop(maxIdx)

print(scoresCopy)
print(scores)
print(f'최고 점수 : {max} index = {maxIdx} ')
print(f'최저 점수 : {min} index = {minIdx} ')

💡result

[9.5, 8.5, 9.0, 7.5, 6.5, 8]
[9.0, 7.5, 6.5, 8]
최고 점수 : 9.5 index = 0 
최저 점수 : 6.5 index = 4 

📌remove() 함수

remove() 함수를 이용하면 특정 아이템을 삭제할 수 있다.

sports = ['농구', '축구', '수구', '골프', '마라톤', '테니스']
print(sports)
sports.remove('수구')
print(sports)

💡result

['농구', '축구', '수구', '골프', '마라톤', '테니스']
['농구', '축구', '골프', '마라톤', '테니스']

remove() 한 개의 아이템만 삭제 가능하다. 만약 삭제하려는 데이터가 두개 이상이라면 while문을 이용하자


sports = ['농구', '축구', '수구', '골프', '마라톤', '수구', '테니스', '수구']

print(sports)
while '수구' in sports:
    sports.remove('수구')

print(sports)

💡result

['농구', '축구', '수구', '골프', '마라톤', '수구', '테니스', '수구']
['농구', '축구', '골프', '마라톤', '테니스']

profile
개발하고싶은사람

0개의 댓글