리스트에 아이템을 추가하자!
students = ['홍길동', '박찬호', '이용규', '박승철', '김지은']
print('students : {}'.format(students))
print('students Length : {}'.format(len(students)))
print('last index : {}'.format(len(students) - 1 ))
students.append('강호동')
print('students : {}'.format(students))
print('students Length : {}'.format(len(students)))
print('last index : {}'.format(len(students) - 1 ))
-->
students : ['홍길동', '박찬호', '이용규', '박승철', '김지은']
students Length : 5
last index : 4
students : ['홍길동', '박찬호', '이용규', '박승철', '김지은', '강호동']
students Length : 6
last index : 5
--
scores = [['국어', 88],
['영어', 91]]
print('scores : {}'.format(scores))
print('scores length: {}'.format(len(scores)))
print('last index: {}'.format(len(scores) - 1))
scores.append(['수학', 96])
print('scores : {}'.format(scores))
print('scores length: {}'.format(len(scores)))
print('last index: {}'.format(len(scores) - 1))
for subject, score in scores:
print('과목: {}, 점수: {}'.format(subject, score))
-->
scores : [['국어', 88], ['영어', 91]]
scores length: 2
last index: 1
scores : [['국어', 88], ['영어', 91], ['수학', 96]]
scores length: 3
last index: 2
과목: 국어, 점수: 88
과목: 영어, 점수: 91
과목: 수학, 점수: 96
myFamilyAge = [['아빠', 40], ['엄마', 38], ['나', 9]]
print(myFamilyAge)
myFamilyAge.append(['동생', 1])
print(myFamilyAge)
for name, age in myFamilyAge:
print('{} : {}'.format(name, age))
-->
[['아빠', 40], ['엄마', 38], ['나', 9]]
[['아빠', 40], ['엄마', 38], ['나', 9], ['동생', 1]]
아빠 : 40
엄마 : 38
나 : 9
동생 : 1
추가하면 리스트의 마지막에 추가됨
students = ['홍길동', '박찬호', '이용규', '박승철', '김지은']
print(students)
students.insert(3, '강호동') #인덱스, 아이템
print(students)
-->
['홍길동', '박찬호', '이용규', '박승철', '김지은']
['홍길동', '박찬호', '이용규', '강호동', '박승철', '김지은']
--
words = ['I', 'a', 'boy.']
for word in words:
print(word, end='')
print()
words.insert(1, 'am')
for word in words:
print('{} '.format(word), end='')
-->
Iaboy.
I am a boy.
--
numbers = [1, 3, 6, 11, 45, 54, 62, 74, 85]
inputNumber = int(input('숫자 입력: '))
insertIdx = 0 #자리에 넣을 인덱스 변수 지정
for idx, number in enumerate(numbers):
print(idx, number)
if insertIdx == 0 and inputNumber < number: #중간값이면 중간에 멈춰서도록 두개 지정
insertIdx = idx #최초 나타난 자리에 인덱스를 할당하겠다
numbers.insert(insertIdx, inputNumber)
print('numbers: {}'.format(numbers))
-->
0 1
1 3
2 6
3 11
4 45
5 54
6 62
7 74
8 85
numbers: [1, 3, 6, 11, 22, 45, 54, 62, 74, 85]