
파이썬을 이용해서 정렬을 해야할 때, sort(), sorted()를 이용해서 쉽게 정렬할 수 있다.
오늘은 이 두 함수의 차이점에 대해 알아보도록 하겠다!
Python lists have a built-in list.sort() method that modifies the list in-place
: 파이썬 리스트는 리스트를 제자리에서 수정하는 내장 메서드list.sort()를 갖는다.
Nonedata = [6, 2, 3, 9]
data.sort()
print(data) # [2, 3, 6, 9]
data = [6, 2, 3, 9]
data.sort(reverse=True)
print(data) # [9, 6, 3, 2]
There is also a sorted() built-in function that builds a new sorted list from an iterable.
:iterable로부터 새로운 정렬된 리스트를 만드는sorted()내장 함수가 있다.
정렬된 리스트iterable에 적용할 수 있다.iterable 객체: 반복 가능한 객체list, dict, set, str, bytes, tuple, rangedata = [6, 2, 3, 9]
new_data = sorted(data)
print(data) # [6, 2, 3, 9]
print(new_data) # [2, 3, 6, 9]
data = [6, 2, 3, 9]
new_data = sorted(data, reverse=True)
print(data) # [6, 2, 3, 9]
print(new_data) # [9, 6, 3, 2]
→ 원래 리스트는 변하지 않았다!
data_str = "yeonju"
new_data = sorted(data_str)
print(''.join(data_str)) # yeonju
print(''.join(new_data)) # ejnouy
→ 문자열은 iterable 객체이므로 sorted를 적용할 수 있다.
sort()는None이 반환된다.sorted()는iterable 객체에 적용할 수 있다.sort()는 리스트의 복사본을 만들 필요가 없어서 sorted()보다 빠르다.
https://docs.python.org/3/howto/sorting.html?highlight=sort
https://wikidocs.net/16068
https://www.acmicpc.net/blog/view/58