Python에서 리스트(List)는 가장 많이 사용되는 자료형 중 하나입니다.
리스트는 여러 개의 값을 하나의 변수에 저장할 수 있는 데이터 구조입니다.
리스트는 대괄호 []로 감싸서 정의하며, 각 요소는 쉼표 ,로 구분합니다.
리스트의 특징:
1) 순서가 있음: 리스트의 요소는 순서가 있으며, 인덱스를 통해 접근할 수 있습니다. 인
덱스는 0부터 시작합니다.
2) 변경 가능(mutable): 리스트는 생성한 후에도 그 값을 변경할 수 있습니다.
3) 다양한 데이터 타입을 저장할 수 있다: 리스트는 다양한 데이터 타입을 저장할 수 있습니다.
리스트의 끝에 요소를 추가한다
fruits = ['apple', 'banana', 'cherry']
fruits.append('orange')
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
리스트에서 "첫 번째" 로 나오는 특정 값을 제거한다.
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits) # ['apple', 'cherry', 'orange']
다른 리스트의 모든 요소를 현재 리스트의 끝에 추가한다.
fruits = ['apple', 'banana', 'cherry']
more_fruits = ['grape', 'melon']
fruits.extend(more_fruits)
print(fruits) # ['apple', 'cherry', 'orange', 'grape', 'melon']
리스트의 특정 인덱스에 있는 값을 변경한다.
fruits = ['apple', 'cherry', 'orange', 'grape', 'melon']
fruits[1] = 'blueberry'
print(fruits) # ['apple', 'blueberry', 'orange', 'grape', 'melon']
특정 인덱스에 있는 요소를 삭제한다.
fruits = ['apple', 'blueberry', 'orange', 'grape', 'melon']
del fruits[2]
print(fruits) # ['apple', 'blueberry', 'grape', 'melon']
특정 위치에 요소를 삽입한다.
리스트의 요소를 역순으로 정렬한다.
fruits = ['apple', 'banana', 'blueberry', 'grape', 'melon']
fruits.reverse()
print(fruits) # ['melon', 'grape', 'blueberry', 'banana', 'apple']
문자열을 리스트로 분리한다.
(매우 유용하게 사용되므로 꼭 알고 있기)
text = "one, two, three"
word_list = text.split(', ')
print(word_list) # ['one', 'two', 'three']