Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags more
Archives
Today
Total
관리 메뉴

냥집사의 개발일지

Python - 파이썬 기본 문법 정리 (list-2) 본문

Python

Python - 파이썬 기본 문법 정리 (list-2)

깅햄찌 2022. 10. 2. 21:05
반응형

안녕하세요 오늘은 지난 시간에 이어 파이썬 자료구조 중 list에 대해 알아보겠습니다~

 

1. list 요소 값으로 list 요소 인덱스 찾기

friends = ['Jeff', 'Alana', 'Electra']

print(friends.index('Jeff'))    
print(friends.index('Alana'))

index() 함수 매개변수로 list의 요소 값을 넣어주면 list 요소 값의 인덱스가 출력됩니다. 

아래 결과 처럼 jeff는 0번째 alana는 1번째 인덱스인 것을 알 수 있습니다. 

2. list 안에 요소 값이 있는지 확인

friends = ['Jeff', 'Alana', 'Electra']

print('Jeff' in friends)    
print('John' in friends)

파이썬 구문 in을 사용하여 list 요소 값의 존재 유무를 파악할 수 있습니다. 

아래 결과 처럼 Jeff는 friends list안에 있는 요소이기에 True, John은 friends list에 없는 요소이므로 False을 출력합니다. 

3. list 요소 값 정렬하기

friends = ['Jeff', 'Alana', 'Electra']
num_arr = [5,3,9,4,1]

sorted_friends = sorted(friends)
sorted_num_arr = sorted(num_arr)

print(friends)
print(num_arr)

print(sorted_friends)
print(sorted_num_arr)

friends.sort()
num_arr.sort()

print(friends)
print(num_arr)

friends.sort(reverse=True)
num_arr.sort(reverse=True)

print(friends)
print(num_arr)

1) sorted()함수에 매개변수로 list를 넣어주면 list의 요소들이 오름차순으로 정렬됩니다. 

2) sort()함수는 list의 요소들을 오름차순으로 정렬합니다. 

    *매개변수에 reversed = Ture를 넣을 시 내림차순으로 정렬됩니다. 

 Tips sort() 와 sorted()의 차이

        sort()는 list 자체를 내부적으로 정렬합니다. 

        sorted()는 정렬된 list를 반환합니다. 

        ex. sorted의 매개변수 list는 정렬되지 않는다!

4. list의 얕은 복사

friends = ['Jeff', 'Alana', 'Electra']
buddies = friends

friends[0] = 'John'

print("friends : ", friends)
print("buddies : ", buddies)

friends = ['Jeff', 'Alana', 'Electra']
buddies = friends.copy()

friends[0] = 'John'

print("friends : ", friends)
print("buddies : ", buddies)

friends = ['Jeff', 'Alana', 'Electra']
buddies = list(friends)

friends[0] = 'John'

print("friends : ", friends)
print("buddies : ", buddies)

friends = ['Jeff', 'Alana', 'Electra']
buddies = friends[:]

friends[0] = 'John'

print("friends : ", friends)
print("buddies : ", buddies)

1) list를 '=' 대입 연산자를 통해 할당했을 때 

    아래 결과 처럼 깊은 복사가 되어 friends의 변화가 buddies에도 영향을 끼칩니다. 

 

2) copy() 함수를 통해 리스트 복사

    아래 결과 처럼 얕은 복사가 되어 friends의 변화가 buddies에 영향을 끼치지 않습니다. 

3) list() 함수를 통해 리스트 복사

    아래 결과 처럼 얕은 복사가 되어 friends의 변화가 buddies에 영향을 끼치지 않습니다. 

3) [:] 슬라이스를 통해 리스트 복사

    아래 결과 처럼 얕은 복사가 되어 friends의 변화가 buddies에 영향을 끼치지 않습니다. 

오늘은 파이썬 자료구조 중 list에 대해 알아보았습니다~

다음 포스팅에서는 tuple에 대해 알아보겠습니다~

좋은 하루 보내세요!!

Comments