sort와 sorted의 차이점

2020. 9. 28. 18:17프로그래밍 언어/Python

반응형

sort와 sorted메서드는 이름은 비슷하지만 서로 다른 역할을 하는 메서드이다.

기본적으로 sort함수는 list 클래스의 메서드로 list객체에서만 사용할 수 있다. 그에 반해 sorted함수는 iterable 객체(list, string, tuple, dictionary 등등...)을 파라미터로 받을 수 있는 메서드이다.

 

그 외에도 두 메서드간의 몇가지 차이점에 대해 알아보자.


sort 메서드

# Syntax:
List_name.sort(key, reverse=False)

# Parameters:
# key: A function that serves as a key for the sort comparison.
# reverse: If true, the list is sorted in descending order.

# Return type:
None

sort 메서드는 위에서 말했듯이 list 클래스의 메서드이다. 따라서 list.sort() 형식으로만 사용할 수 있다.

 

실행 시 기본적으로 오름차순으로 리스트 객체 자체를 정렬하며 반환하는 값은 None이다.

list1 = list2.sort() # 실수

따라서, 위와 같은 코드는 옳지 않다.

 

keyreverse파라미터를 조정해서 정렬 기준을 변경 할 수 있다.


sorted 메서드

# Syntax:
sorted(iterable, key, reverse=False)

# Parameters:
# Iterable: sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
# Key(optional): A function that would serve as a key or a basis of sort comparison.
# Reverse(optional): If set True, then the iterable would be sorted in reverse (descending) order, by default it is set as False.

# Return Type:
list

sorted 메서드는 iterable 객체를 파라미터로 받는 메서드이며 대표적인 iterable로는 list, tuple, string, dict, set등이 있다.

 

실행 시 기본적으로 sort 메서드와 같이 오름차순으로 객체를 정렬하고 정렬된 iterable을 반환하는게 sort 메서드와의 가장 큰 차이점이다.

list1 = sorted(list2) # 가능

따라서, 위와 같은 코드는 올바른 코드이다.

 

sort 메서드처럼 key와 reverse파라미터를 조정해서 정렬 기준을 변경 할 수 있다.


sort vs sorted?

두 메서드 모두 기본적인 사용법은 유사하다.

list 객체에서는 두 메서드 모두 사용 가능하고 정렬한다는 것도 같다. 그렇다면 성능 차이는 어떨까?

 

결론은 sort 메서드가 미세하게 더 빠르다. 계산이 많지 않을때는 case by case이지만 계산량이 많아지면 sorted는 새로운 객체를 생성해야하는 오버헤드가 있어서 sort보다 시간이 더 걸리는 것이다.

 

하지만 두 메서드는 애초에 반환값이 다른 메서드이므로 용도가 다르다.

sort는 기존의 list의 정렬 정보가 필요없고 그 객체 자체를 정렬하고 싶을때 사용하고, sorted는 기존 list의 정렬 정보가 유의미하고 다른 객체를 생성해 저장하고 싶을때 사용하면 된다.

 

list가 아닌 iterable에서는 어쩔 수 없이 sorted를 사용해야 한다.


참조

https://stackoverflow.com/questions/22442378/what-is-the-difference-between-sortedlist-vs-list-sort
 

What is the difference between `sorted(list)` vs `list.sort()`?

list.sort() sorts the list and replaces the original list, whereas sorted(list) returns a sorted copy of the list, without changing the original list. When is one preferred over the other? Which i...

stackoverflow.com

https://www.geeksforgeeks.org/python-difference-between-sorted-and-sort/
 

Python - Difference between sorted() and sort() - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

반응형