[python] 파이썬: sort, sorted 차이점
sort, sorted 차이점
1. sorted란
iterable한 값을 정렬하여 새로운 리스트를 리턴합니다.
새로운 리스트를 만들어 반환하기 때문에 원본 리스트에 영향을 미치지 않습니다.
모든 iterable에서 동작합니다.
※ iterable이란 list, str 등 요소 하나하나를 반환할 수 있는 object
l1 = [100, 20, 1, 30, 2]
l2 = sorted(l1)
print("l1: {0}".format(l1))
print("l2: {0}".format(l2))
# 출력
# l1: [100, 20, 1, 30, 2]
# l2: [1, 2, 20, 30, 100]
l2 = sorted(l1)
print("l1: {0}".format(l1))
print("l2: {0}".format(l2))
# 출력
# l1: [100, 20, 1, 30, 2]
# l2: [1, 2, 20, 30, 100]
새로운 리스트를 만들어 반환하기 때문에 새로운 l2 list가 정렬되었으며 기존에 l1 list는 정렬되지 않았습니다.
2. sort란
list 안에 값을 in place로 정렬합니다.
※ in-place란 할당된 list를 직접 변경합니다. 이는 새로운 list를 메모리에 생성하지 않음을 의미합니다.
l1 = [100, 20, 1, 30, 2]
l2 = l1.sort()
print("l1: {0}".format(l1))
print("l2: {0}".format(l2))
# 출력
# l1: [1, 2, 20, 30, 100]
# l2: None
l2 = l1.sort()
print("l1: {0}".format(l1))
print("l2: {0}".format(l2))
# 출력
# l1: [1, 2, 20, 30, 100]
# l2: None
메모리에 할당되어 있는 l1 list를 정렬합니다. 새로운 list를 생성하지 않기 때문에 return 값은 None이 출력됩니다.
3. sort, sorted 차이점
sort는 list에서만 사용할 수 있지만 sorted는 list 이외 iterable한 값에서도 사용가능합니다.
l1 = "bca"
l2 = sorted(l1)
print("l2: {0}".format(l2))
# 출력
# l2: ['a', 'b', 'c']
l1 = "bca"
l1.sort()
print("l1: {0}".format(l1))
# 출력
# AttributeError: 'str' object has no attribute 'sort'
l2 = sorted(l1)
print("l2: {0}".format(l2))
# 출력
# l2: ['a', 'b', 'c']
l1 = "bca"
l1.sort()
print("l1: {0}".format(l1))
# 출력
# AttributeError: 'str' object has no attribute 'sort'
sort는 새로운 메모리 할당이 이뤄지지 않기 때문에 sorted보다 속도가 더 빠릅니다.
sort는 기존에 list 값을 변경하기 때문에 한번 변경하면 이 전의 값으로 돌아갈 수 없습니다.
기존에 list를 변경하지 않고 정렬을 하고 싶다면 sorted를
기존에 list를 변경해도 되면 sort를 사용하면 됩니다.
sorted는 새로운 메모리 할당 후, sort는 할당된 메모리에서 정렬이 이루어짐을 기억하시면 됩니다.
참고문헌
[1] https://docs.python.org/3/library/functions.html#sorted
[2] https://docs.python.org/3/tutorial/datastructures.html
[3] https://stackoverflow.com/questions/22442378/what-is-the-difference-between-sortedlist-vs-list-sort
[2] https://docs.python.org/3/tutorial/datastructures.html
[3] https://stackoverflow.com/questions/22442378/what-is-the-difference-between-sortedlist-vs-list-sort
댓글
댓글 쓰기