[자료구조] List의 insert() 함수

신은지·2024년 7월 10일

Data Structure

목록 보기
8/31
post-thumbnail

insert() 함수

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

words = ['I', 'a', 'boy.']
words.insert(1, 'am')

for word in words:
	print('{}'.format(word), end='')

💡Python으로 insert() 함수를 이용해 추가 아이템 위치 지정하기

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

numbers = [1, 3, 6, 11, 45, 54, 62, 74, 85]
inputNum = int(input("숫자: "))
targetIdx = 0

for idx, num in enumerate(numbers):
    print(idx, num)

    if targetIdx == 0 and inputNum < num:
        targetIdx = idx

numbers.insert(targetIdx, inputNum)
print(numbers)





* 이 글은 제로베이스 데이터 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다.

profile
I believe there is no best, only better

0개의 댓글