Development Tip

Python 강좌 04 - List

MoonLight314 2024. 12. 23. 11:01
728x90

이번 강좌는 Python의 List에 관해서 알아보도록 하겠습니다.

 

 

1. 기본 사항

Python의 List는 여러 값을 저장할 수 있는 데이터 구조로, 순서가 있는 변경 가능한(collection) 객체입니다.

List는 Python에서 가장 널리 사용되는 데이터 구조 중 하나로, 다양한 방식으로 데이터를 다룰 수 있습니다.

List는 값의 순서가 중요하며, 값들이 Index를 통해 접근됩니다.

List 내의 값은 서로 다른 데이터 타입일 수 있습니다.

 

1.1. 기본 개념

순서가 있음 : List는 삽입된 순서대로 값을 저장합니다.

변경 가능 : List는 값을 추가하거나 삭제할 수 있습니다.

Index 사용 : 각 요소는 Index를 통해 접근할 수 있습니다. (Index는 0부터 시작)

혼합 데이터 타입 : List는 문자열, 숫자, 객체 등 다양한 데이터 타입을 혼합해서 저장할 수 있습니다.

 

 

 

1.2. List 생성 방법

# 빈 List 생성
my_list = []

# 값이 있는 List 생성
fruits = ["apple", "banana", "cherry"]
print(fruits) # 출력: ['apple', 'banana', 'cherry']

 

1.3. List에 요소 추가

append()

- List의 끝에 요소를 추가합니다.

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # 출력: ['apple', 'banana', 'cherry', 'orange']

insert()

- 특정 위치에 요소를 삽입합니다. 첫 번째 인자로 Index를, 두 번째 인자로 삽입할 값을 받습니다.

fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "orange") # 1번 Index에 "orange" 삽입
print(fruits) # 출력: ['apple', 'orange', 'banana', 'cherry']

extend()

- 다른 List나 이터러블 객체의 요소를 현재 List에 추가합니다.

fruits = ["apple", "banana"]
more_fruits = ["cherry", "orange"]
fruits.extend(more_fruits)
print(fruits) # 출력: ['apple', 'banana', 'cherry', 'orange']

 

 

1.4. List에서 요소 제거

remove()

- List에서 첫 번째로 일치하는 요소를 제거합니다. 요소가 없으면 ValueError가 발생합니다.

fruits = ["apple", "banana", "cherry", "banana"]
fruits.remove("banana")
print(fruits) # 출력: ['apple', 'cherry', 'banana']

pop()

- List에서 지정된 Index에 있는 요소를 제거하고 반환합니다. Index를 생략하면 마지막 요소를 제거하고 반환합니다.

fruits = ["apple", "banana", "cherry"]
removed_item = fruits.pop(1) # Index 1에 있는 "banana" 제거
print(fruits) # 출력: ['apple', 'cherry']
print(removed_item) # 출력: banana

del

- 지정된 Index의 요소를 삭제하거나, 전체 List를 삭제할 수 있습니다.

fruits = ["apple", "banana", "cherry"]
del fruits[1] # Index 1의 "banana" 삭제
print(fruits) # 출력: ['apple', 'cherry']

# 전체 List 삭제
del fruits
# print(fruits) # 오류 발생: NameError

 

 

1.5. List 접근 및 슬라이싱

인덱싱

- List의 각 요소는 Index를 통해 접근할 수 있습니다. Index는 0부터 시작합니다.

fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # 출력: apple
print(fruits[1]) # 출력: banana
print(fruits[-1]) # 출력: cherry (음수 Index는 끝에서부터 접근)

슬라이싱

- List의 부분을 잘라서 새로운 List를 반환합니다.

fruits = ["apple", "banana", "cherry", "date", "elderberry"]
print(fruits[1:4])
출력
['banana', 'cherry', 'date'] (Index 1부터 3까지)

print(fruits[:3])
출력
['apple', 'banana', 'cherry'] (처음부터 3번 Index 직전까지)

print(fruits[2:])
출력: 
['cherry', 'date', 'elderberry'] (2번 Index부터 끝까지)

 

 

1.6. List의 길이와 반복

len()

- List의 길이(요소의 개수)를 반환합니다.

fruits = ["apple", "banana", "cherry"]
print(len(fruits))

출력:
3

반복문을 이용한 List 순회

List의 요소를 하나씩 처리할 수 있습니다.

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

출력:
apple
banana
cherry

 

List 컴프리헨션

List 컴프리헨션을 사용하면 간결하게 List를 생성할 수 있습니다.

# 1부터 10까지의 제곱수를 포함한 List
squares = [x ** 2 for x in range(1, 11)]
print(squares)

출력:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

 

1.7. List 정렬 및 역순

sort()

- List를 오름차순으로 정렬합니다. reverse=True를 설정하면 내림차순으로 정렬됩니다.

fruits = ["banana", "cherry", "apple"]
fruits.sort()
print(fruits)

출력: 
['apple', 'banana', 'cherry']

# 내림차순 정렬
fruits.sort(reverse=True)
print(fruits)

출력:
['cherry', 'banana', 'apple']

sorted()

- sorted()는 List를 정렬한 새로운 List를 반환하고, 원본 List는 변경하지 않습니다.

fruits = ["banana", "cherry", "apple"]
sorted_fruits = sorted(fruits)
print(sorted_fruits)

출력: 
['apple', 'banana', 'cherry']

print(fruits)
출력: 
['banana', 'cherry', 'apple'] (원본 List는 변하지 않음)

reverse()

- List를 반대로 뒤집습니다.

fruits = ["banana", "cherry", "apple"]
fruits.reverse()
print(fruits)

출력:
['apple', 'cherry', 'banana']

 

 

1.8. List 결합 및 복사

+ 연산자 (List 결합)

List를 결합할 때 + 연산자를 사용할 수 있습니다.

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

출력
[1, 2, 3, 4, 5, 6]

* 연산자 (List 반복)

List를 반복하려면 * 연산자를 사용합니다.

numbers = [1, 2, 3]
repeated_list = numbers * 3
print(repeated_list)

출력
[1, 2, 3, 1, 2, 3, 1, 2, 3]

copy()

List의 복사본을 만들 때 copy() 메서드를 사용합니다.

fruits = ["apple", "banana", "cherry"]
fruits_copy = fruits.copy()
print(fruits_copy)

출력
['apple', 'banana', 'cherry']

 

1.9. List 관련 유용한 함수들​

min()

- List에서 가장 작은 값을 반환합니다.

numbers = [10, 20, 4, 45, 99]
print(min(numbers))

출력
4

max()

- List에서 가장 큰 값을 반환합니다.

numbers = [10, 20, 4, 45, 99]
print(max(numbers))

출력
99

sum()

- List의 모든 요소의 합을 반환합니다.

numbers = [10, 20, 30]
print(sum(numbers))

출력
60

any()

- List에 하나라도 True가 있으면 True를 반환합니다.

print(any([False, False, True]))

출력
True

all()

- List의 모든 요소가 True일 때 True를 반환합니다.

print(all([True, True, True]))

출력
True

join()

- join 메서드는 문자열(iterable)을 특정 구분자로 결합하여 새로운 문자열을 생성하는 데 사용됩니다.

join은 List, Tuple, 문자열 등의 iterable 요소들을 하나의 문자열로 합칠 때 유용합니다.

기본 문법

"구분자".join(iterable)

구분자 : 결합할 문자열의 각 요소 사이에 들어갈 구분자 문자열.

iterable : 문자열로 구성된 반복 가능한 객체(예: List, 튜플, 문자열).

기본 예제

1. List 요소를 문자열로 합치기

words = ["Hello", "World", "Python"]
result = " ".join(words) # 공백을 구분자로 사용
print(result)

출력:
Hello World Python

2. 다른 구분자 사용

numbers = ["1", "2", "3", "4"]
result = "-".join(numbers) # 하이픈(-)으로 결합
print(result)

출력:
1-2-3-4

 

중요 사항

join의 대상(iterable)은 문자열로 이루어져야 합니다.

만약 문자열이 아닌 객체가 포함되어 있다면, TypeError가 발생합니다.​

items = [1, 2, 3]
result = ",".join(items) # 오류 발생 (TypeError)

해결 방법: 문자열이 아닌 객체를 문자열로 변환해야 합니다.​

items = [1, 2, 3]
result = ",".join(map(str, items)) # 모든 요소를 문자열로 변환
print(result)

출력:
1,2,3

 

 

 

2. 예제

 

 

Ex. 1. 2016년 11월 영화 예매 순위 기준 top3는 다음과 같습니다.
영화 제목을 movie_rank 이름의 List에 저장해보세요. (순위 정보는 저장하지 않습니다.)

 

순위
영화
1
닥터 스트레인지
2
스플릿
3
럭키
movie_rank = ["닥터 스트레인지", "스플릿", "럭키"]

 

 

Ex. 2. 051의 movie_rank List에 "배트맨"을 추가하라.

movie_rank = ["닥터 스트레인지", "스플릿", "럭키"]
movie_rank.append("배트맨")
print(movie_rank)

출력:
['닥터 스트레인지', '스플릿', '럭키', '배트맨']

List에 추가하는 Method는 append()입니다.

 

 

Ex. 3. movie_rank List에는 아래와 같이 네 개의 영화 제목이 바인딩되어 있다. "슈퍼맨"을 "닥터 스트레인지"와 "스플릿" 사이에 추가하라.

movie_rank = ['닥터 스트레인지', '스플릿', '럭키', '배트맨']
movie_rank.insert(1,'슈퍼맨')
print(movie_rank)

출력:
['닥터 스트레인지', '슈퍼맨', '스플릿', '럭키', '배트맨']

List의 `insert(Index, 원소)` 메서드를 사용하면 특정 위치에 값을 끼어넣기 할 수 있습니다.

 

 

Ex. 4. movie_rank List에서 '럭키'를 삭제하라.

movie_rank = ['닥터 스트레인지', '슈퍼맨', '스플릿', '럭키', '배트맨']
movie_rank.remove('럭키')
print(movie_rank)

출력:
['닥터 스트레인지', '슈퍼맨', '스플릿', '배트맨']

 

Ex. 5. movie_rank List에서 '스플릿' 과 '배트맨'을 를 삭제하라.

movie_rank = ['닥터 스트레인지', '슈퍼맨', '스플릿', '배트맨']
movie_rank.remove('스플릿')
movie_rank.remove('배트맨')
print(movie_rank)

출력:
['닥터 스트레인지', '슈퍼맨']

 

 

Ex. 6. lang1과 lang2 List가 있을 때 lang1과 lang2의 원소를 모두 갖고 있는 langs List를 만들어라.

lang1 = ["C", "C++", "JAVA"]

lang2 = ["Python", "Go", "C#"]

lang1 = ["C", "C++", "JAVA"]
lang2 = ["Python", "Go", "C#"]

print((lang1+lang2))

출력:
['C', 'C++', 'JAVA', 'Python', 'Go', 'C#']

두 List를 더하면 새로운 List가 생성됩니다.

 

Ex. 7. 다음 List에서 최댓값과 최솟값을 출력하라. (힌트: min(), max() 함수 사용)

nums = [1, 2, 3, 4, 5, 6, 7]
nums = [1, 2, 3, 4, 5, 6, 7]
print(max(nums),min(nums))

출력:
7 1

 

 

Ex. 8. 다음 List의 합을 출력하라.

nums = [1, 2, 3, 4, 5]
nums = [1, 2, 3, 4, 5]
print(sum(nums))

출력:
15

 

 

Ex. 9. 다음 List에 저장된 데이터의 개수를 화면에 구하하라.

cook = ["피자", "김밥", "만두", "양념치킨", "족발", "피자", "김치만두", "쫄면", "소시지", "라면", "팥빙수", "김치전"]
print(len(cook))

출력:
12

 

Ex. 10. 다음 List의 평균을 출력하라.

nums = [1, 2, 3, 4, 5]

nums = [1, 2, 3, 4, 5]
print(sum(nums)/len(nums))

출력:
3.0

 

 

Ex. 11. price 변수에는 날짜와 종가 정보가 저장돼 있다.

날짜 정보를 제외하고 가격 정보만을 출력하라. (힌트 : 슬라이싱)

 

price = ['20180728', 100, 130, 140, 150, 160, 170]

price = ['20180728', 100, 130, 140, 150, 160, 170]
print(price[1:])

출력:
[100, 130, 140, 150, 160, 170]

 

Ex. 12. 슬라이싱을 사용해서 홀수만 출력하라.

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(nums[::2])

출력:
[1, 3, 5, 7, 9]

 

Ex. 13. 슬라이싱을 사용해서 짝수만 출력하라.

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(nums[1::2])

출력:
[2, 4, 6, 8, 10]

 

Ex. 14. 슬라이싱을 사용해서 List의 숫자를 역 방향으로 출력하라.

nums = [1, 2, 3, 4, 5]

nums = [1, 2, 3, 4, 5]
print(nums[::-1])

출력:
[5, 4, 3, 2, 1]

 

 

Ex. 15. interest List에는 아래의 데이터가 바인딩되어 있다.

interest = ['삼성전자', 'LG전자', 'Naver']

interest List를 사용하여 아래와 같이 화면에 출력하라.

출력 예시:

삼성전자 Naver

interest = ['삼성전자', 'LG전자', 'Naver']
print(interest[::2])

출력:
['삼성전자', 'Naver']

 

 

Ex. 16. interest List에는 아래의 데이터가 바인딩되어 있다.

interest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']

interest List를 사용하여 아래와 같이 화면에 출력하라.

출력 예시:

삼성전자 LG전자 Naver SK하이닉스 미래에셋대우

interest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']
print(" ".join(interest))

출력:
삼성전자 LG전자 Naver SK하이닉스 미래에셋대우

 

 

Ex. 17. interest List에는 아래의 데이터가 바인딩되어 있다.

interest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']

interest List를 사용하여 아래와 같이 화면에 출력하라.

출력 예시:

삼성전자/LG전자/Naver/SK하이닉스/미래에셋대우

interest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']
print("/".join(interest))

출력:
삼성전자/LG전자/Naver/SK하이닉스/미래에셋대우

 

 

Ex. 18. interest List에는 아래의 데이터가 바인딩되어 있다.

interest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']

join() 메서드를 사용해서 interest List를 아래와 같이 화면에 출력하라.

출력 예시:

삼성전자

LG전자

Naver

SK하이닉스

미래에셋대우

interest = ['삼성전자', 'LG전자', 'Naver', 'SK하이닉스', '미래에셋대우']
print("\n".join(interest))

출력:
삼성전자
LG전자
Naver
SK하이닉스
미래에셋대우

 

Ex. 19. 회사 이름이 슬래시 ('/')로 구분되어 하나의 문자열로 저장되어 있다.

string = "삼성전자/LG전자/Naver"

이를 interest 이름의 List로 분리 저장하라.

실행 예시

['삼성전자', 'LG전자', 'Naver']

string = "삼성전자/LG전자/Naver"
print(string.split("/"))

출력:
['삼성전자', 'LG전자', 'Naver']

 

Ex. 20. List에 있는 값을 오름차순으로 정렬하세요.

data = [2, 4, 3, 1, 5, 10, 9]

data = [2, 4, 3, 1, 5, 10, 9]
data.sort()
print(data)
data = [2, 4, 3, 1, 5, 10, 9]
print(sorted(data))

출력:
[1, 2, 3, 4, 5, 9, 10]
728x90

'Development Tip' 카테고리의 다른 글

Python 강좌 06 - Dictionary  (0) 2024.12.23
Python 강좌 05 - Tuple  (0) 2024.12.23
Python 강좌 03 - 문자열  (0) 2024.12.23
Python 강좌 02 - 변수  (0) 2024.12.23
Python 강좌 01 - print()  (0) 2024.12.22