본문 바로가기

python

python - 리스트 기본 사용법

1. 리스트 기본 생성 및 사용

* 리스트의 생성 : 대괄호 [ ]

* 다양한 자료형 저장 가능

# 리스트 생성
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "apple", True, [10, 20]]

print(numbers)  # [1, 2, 3, 4, 5]
print(fruits)   # ['apple', 'banana', 'cherry']
print(mixed)    # [1, 'apple', True, [10, 20]]

 

2. 리스트 연산

(1) 리스트 더하기 : 두 리스트 이어 붙임

list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2
print(result)  # [1, 2, 3, 4, 5, 6]

(2) 리스트 곱하기 : 리스트 반복하여 새로운 리스트 생성

list1 = [1, 2, 3]
result = list1 * 3
print(result)  # [1, 2, 3, 1, 2, 3, 1, 2, 3]

(3) 포함 여부 확인 (in 연산자) : 리스트에 특정 값이 있는지 확인 - 결과 true or false

fruits = ["apple", "banana", "cherry"]
print("apple" in fruits)   # True
print("grape" in fruits)   # False

#not in 연산자
print("grape" not in fruits)  # True

 

3. 리스트 주요 메소드

메소드  설명 예제
append(x) 리스트 끝에 요소 추가 list.append(4)
insert(i, x) 특정 위치에 요소 삽입 list.insert(1,100)
extend(iterable) 리스트 확장 list.extend([4,51])
remove(x) 특정 값 삭제 (첫 번째 등장만) list.remove(2)
pop([i]) 특정 인덱스의 요소 제거 (기본값: 마지막) list.pop()
index(x) 특정 값의 첫 번째 인덱스 반환 list.index(3)
count(x) 특정 값의 개수 반환 list.count(2)
sort() 리스트를 정렬 (기본: 오름차순) list.sort()
reverse() 리스트를 역순으로 변경 list.reverse()
clear() 리스트의 모든 요소 삭제 list.clear()

 

예제)

# 초기 리스트
fruits = ["apple", "banana"]
print("초기 리스트:", fruits)
# 초기 리스트: ['apple', 'banana']

# append: 끝에 요소 추가
fruits.append("cherry")
print("append 후:", fruits)
# append 후: ['apple', 'banana', 'cherry']

# insert: 특정 위치에 요소 추가
fruits.insert(1, "kiwi")
print("insert 후:", fruits)
# insert 후: ['apple', 'kiwi', 'banana', 'cherry']

# extend: 리스트 확장
fruits.extend(["orange", "grape"])
print("extend 후:", fruits)
# extend 후: ['apple', 'kiwi', 'banana', 'cherry', 'orange', 'grape']

# remove: 특정 값 삭제
fruits.remove("banana")
print("remove 후:", fruits)
# remove 후: ['apple', 'kiwi', 'cherry', 'orange', 'grape']

# pop: 마지막 요소 제거
last_item = fruits.pop()
print("pop 후:", fruits)
# pop 후: ['apple', 'kiwi', 'cherry', 'orange']
print("제거된 값:", last_item)
# 제거된 값: grape

# index: 특정 값의 첫 번째 인덱스 찾기
kiwi_index = fruits.index("kiwi")
print("kiwi의 인덱스:", kiwi_index)
# kiwi의 인덱스: 1

# count: 특정 값의 등장 횟수
apple_count = fruits.count("apple")
print("apple의 개수:", apple_count)
# apple의 개수: 1

# sort: 정렬
fruits.sort()
print("sort 후:", fruits)
# sort 후: ['apple', 'cherry', 'kiwi', 'orange']

# reverse: 역순 정렬
fruits.reverse()
print("reverse 후:", fruits)
# reverse 후: ['orange', 'kiwi', 'cherry', 'apple']

# clear: 리스트 초기화
fruits.clear()
print("clear 후:", fruits)
# clear 후: []

 

 

4. 반복문을 사용한 리스트 생성 및 처리

(1) 반복문으로 리스트 생성

* 리스트 컴프리헨션 : 반복문과 조건문을 사용하여 간결하게 리스트를 생성합니다.

# 1부터 10까지 숫자의 제곱을 저장하는 리스트
squares = [x**2 for x in range(1, 11)]
print(squares)  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# 1부터 10까지 숫자 중 짝수만 저장
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers)  # [2, 4, 6, 8, 10]

 

(2) 반복문으로 리스트 처리

# 리스트의 각 요소 출력
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# 인덱스와 함께 출력
for i in enumerate(fruits):
    print(i[0], i[1])

for i, fruit in enumerate(fruits):
    print(i, fruit)

 

5. 주요 내장 함수

함수 설명 예제
len() 리스트의 길이(요소 개수)를 반환 len([1, 2, 3]) → 3
min() 리스트에서 최소값 반환 min([3, 1, 4]) → 1
max() 리스트에서 최대값 반환 max([3, 1, 4]) → 4
sum() 리스트의 모든 요소의 합 반환 sum([1, 2, 3]) → 6
sorted() 리스트를 정렬하여 새로운 리스트 반환 sorted([3, 1, 4]) → [1, 3, 4]
reversed() 리스트를 역순으로 반환 (반복 가능한 객체로 반환) list(reversed([1, 2, 3])) → [3, 2, 1]

 

예제)

numbers = [10, 20, 30, 40]
print("리스트의 길이:", len(numbers))  # 4

numbers = [10, 20, 5, 40]
print("최소값:", min(numbers))  # 5

numbers = [10, 20, 5, 40]
print("최대값:", max(numbers))  # 40

numbers = [10, 20, 30, 40]
print("합계:", sum(numbers))  # 100

numbers = [40, 10, 30, 20]
print("정렬된 리스트:", sorted(numbers))  # [10, 20, 30, 40]
print("내림차순 정렬:", sorted(numbers, reverse=True))  # [40, 30, 20, 10]

numbers = [10, 20, 30, 40]
print("역순 리스트:", list(reversed(numbers)))  # [40, 30, 20, 10]