Python 복습 (11) : 리스트

STUDY_J·2024년 7월 17일

리스트

Python에서 리스트(List)는 가장 많이 사용되는 자료형 중 하나입니다.
리스트는 여러 개의 값을 하나의 변수에 저장할 수 있는 데이터 구조입니다.
리스트는 대괄호 []로 감싸서 정의하며, 각 요소는 쉼표 ,로 구분합니다.

리스트의 특징:
1) 순서가 있음: 리스트의 요소는 순서가 있으며, 인덱스를 통해 접근할 수 있습니다. 인
덱스는 0부터 시작합니다.
2) 변경 가능(mutable): 리스트는 생성한 후에도 그 값을 변경할 수 있습니다.
3) 다양한 데이터 타입을 저장할 수 있다: 리스트는 다양한 데이터 타입을 저장할 수 있습니다.

주요 메서드

1) append()

리스트의 끝에 요소를 추가한다

fruits = ['apple', 'banana', 'cherry']

fruits.append('orange')
print(fruits)  # ['apple', 'banana', 'cherry', 'orange']

2) remove()

리스트에서 "첫 번째" 로 나오는 특정 값을 제거한다.

  • remove('제거할 문자')
fruits = ['apple', 'banana', 'cherry']

fruits.remove('banana')
print(fruits)  # ['apple', 'cherry', 'orange']

3) extend()

다른 리스트의 모든 요소를 현재 리스트의 끝에 추가한다.

  • extend('추가 리스트')
fruits = ['apple', 'banana', 'cherry']

more_fruits = ['grape', 'melon']
fruits.extend(more_fruits)
print(fruits)  # ['apple', 'cherry', 'orange', 'grape', 'melon']

4) 요소 변경

리스트의 특정 인덱스에 있는 값을 변경한다.

fruits =  ['apple', 'cherry', 'orange', 'grape', 'melon']
fruits[1] = 'blueberry'
print(fruits)  # ['apple', 'blueberry', 'orange', 'grape', 'melon']

5) del()

특정 인덱스에 있는 요소를 삭제한다.

  • del list[인덱스]
fruits = ['apple', 'blueberry', 'orange', 'grape', 'melon']
del fruits[2]
print(fruits)  # ['apple', 'blueberry', 'grape', 'melon']

6) insert()

특정 위치에 요소를 삽입한다.

  • insert(위치, '추가할 요소')

7) reverse()

리스트의 요소를 역순으로 정렬한다.

  • reverse()
fruits = ['apple', 'banana', 'blueberry', 'grape', 'melon']

fruits.reverse()
print(fruits)  # ['melon', 'grape', 'blueberry', 'banana', 'apple']

8) split()

문자열을 리스트로 분리한다.
(매우 유용하게 사용되므로 꼭 알고 있기)

  • split('분리할 텍스트')
  • ex) 예를 들어 문자열을 리스트 형식으로 변환하고, 몇 번째의 단어를 출력하는 문제 같은 경우에 많이 쓰임
text = "one, two, three"
word_list = text.split(', ')
print(word_list)  # ['one', 'two', 'three']

0개의 댓글