본문 바로가기

Python

[파이썬의 시작] 리스트 #2 - 리스트 메서드 적용

◐ 파이썬의 시작 - 리스트


#2 리스트 메서드 적용

'color' 리스트에 몇 가지 리스트 메서드를 적용해 보겠습니다.

먼저 리스트를 지정하고 print() 내장 함수를 사용해서 화면에 출력합니다. 그리고 len() 내장 함수로 리스트 안에 몇 개의 항목이 들어있는지 확인합니다.
4개의 항목이 들어 있는 것을 len() 내장 함수로 확인했습니다.
>>> color=["red", "orange", "blue", "green"]
>>> print(color)
['red', 'orange', 'blue', 'green']
>>> print(len(color))
4


append() 리스트 메서드를 이용하면 리스트 맨 뒤에 데이터 항목을 하나 추가할 수 있습니다.
pop() 메서드는 제일 끝 항목을 삭제하고, extend() 메서드는 여러 데이터 항목을 리스트 제일 뒤에 추가할 수 있습니다.

>>> color.append("white")
>>> print(color)
['red', 'orange', 'blue', 'green', 'white']
>>> color.pop()
'white'
>>> print(color)
['red', 'orange', 'blue', 'green']
>>> color.extend(["white", "black"])
>>> print(color)
['red', 'orange', 'blue', 'green', 'white', 'black']


remove() 메서드로 특정 데이터 항목을 제거할 수 있고, insert() 메서드로 특정 항목 앞에 데이터를 추가할 수 있습니다.
remove() 메서드를 통해 'blue'를 지우고 색인 번호 3인 'white' 앞에 'blue'를 추가 시켰습니다.

>>> color.remove("blue")
>>> print(color)
['red', 'orange', 'green', 'white']
>>> color.insert(3, "blue")
>>> print(color)
['red', 'orange', 'green', 'blue', 'white', 'black']