프로그래밍 언어/Python
리스트 insert() 함수(파이썬)
ruby-jieun
2023. 1. 22. 22:10
insert() 함수
insert() 함수를 이용하면 특정 위치(인덱스)에 아이템을 추가할 수 있다.
students = ['홍길동', '박찬호', '이용규', '박승철', '김지은']
students.insert(3, '강호동')
print('students : {}'.format(students))
print('students의 길이 : {}'.format(len(students)))
print('students의 마지막 인덱스 : {}'.format(len(students) -1))
students : ['홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은']
students의 길이 : 6
students의 마지막 인덱스 : 5
words = ['Ruby', 'studying', 'again', 'today.']
words.insert(1, 'is')
for word in words:
print('{}'.format(word), end = ' ')
Ruby is studying again today.
오름차순으로 정렬되어 있는 숫자들에 사용자가 입력한 정수를 추가하는 프로그램을 만들어보자.
(단, 추가 후에도 오름차순 정렬이 유지되어야 한다.)
numbers = [1, 3, 6, 11, 45, 54, 62, 74, 85]
inputnumber = int(input('숫자 입력: '))
insertIdx = 0
for idx, number in enumerate(numbers):
if insertIdx == 0 and inputnumber < number:
insertIdx = idx
numbers.insert(insertIdx, inputnumber)
print(numbers)
숫자 입력: 55
[1, 3, 6, 11, 45, 54, 55, 62, 74, 85]