ROKO

[Python] LIST.sort() vs sorted(LIST) 본문

Develop

[Python] LIST.sort() vs sorted(LIST)

RO_KO 2023. 3. 2. 00:36
728x90

Python에서 list를 정렬하는 방식은 LIST.sort() 와 sorted(LIST) 2가지 방식이 있다.

두개의 차이점은 무엇이고 어떤것이 더 효율적일까?

 

LIST.sort()

우선 LIST.sort()는 리스트 메서드로 inplace형식이다. 실행한 list자체가 값이 수정되므로 return 값이 None이다.

list1 = [4, 3, 2, 1]
list2 = list1.sort()


print(list1) # [1, 2, 3, 4]
print(list2) # None

sorted(LIST)

sorted는 python 표준 내장 함수로 inplace형식이 아니라 정렬된 새로운 객체를 반환한다.

list1 = [4, 3, 2, 1]
list2 = sorted(list1)


print(list1) # [4, 3, 2, 1]
print(list2) # [1, 2, 3, 4]

두 메서드 모두 stable을 보장한다. 정렬 중 같은 값이 있는 경우 기존의 대소관계를 고려해준다는 뜻이다.

LIST.sort() 와 sorted(LIST) options

  • reverse (default = False)
    • boolean값으로 default값인 ascend를 사용할지 아니면 True로 변환해 descend 기준을 사용할지 결정할 수 있다.
  • key
    • key = "standard"를 하면 내가 임의로 정의한 standard를 기준으로 정렬을 시행한다.
    • 만약 standard 기준이 여러가지일 경우 첫번째 기준으로 정렬뒤 같은 값들은 두번째 기준으로 정렬을 시행하게 된다.

예제는 아래 블로그를 참고하자

https://leedakyeong.tistory.com/entry/python-튜플-정렬하기두-번째-원소로-정렬하기-tuple-sorting-in-python

 

[python] 튜플 정렬하기(두 번째 원소로 정렬하기) :: tuple sorting in python

파이썬에서 튜플 정렬하는 방법 > v = [(3, 4), (2, 2), (3, 3), (1, 2), (1, -1)]> print(v) [(3, 4), (2, 2), (3, 3), (1, 2), (1, -1)] 1. 첫 번째 원소로 오름차순 정렬하기 > v = [(3, 4), (2, 2), (3, 3), (1, 2), (1, -1)] > v.sort(key =

leedakyeong.tistory.com

 

결론

리스트를 기준으로 본다면 LIST.sort()가 inplace로 실행되기에 더 빠르다. 하지만 기존 리스트를 다시 사용해야 할 경우 sorted(LIST)를 사용해야 할 것이다.

 

sorted()만의 장점은 없을까?

바로 리스트 뿐만이 아닌 다양한 iterator에 적용가능하다는 것이다. sort()는 리스트 내장 메서드로 리스트가 아닌 자료구조형에서는 사용할 수 없지만 sorted()는 반복가능한 객체라면 어디에서든 적용이 가능하다.

 

항상 어떠한 것이 좋다기 보다는 목적에 따라 가장 알맞는 방식을 선택하면 될 것 같다.

 

sort(), sorted() document

자세한 sort() 활용법 예시

https://docs.python.org/ko/3/howto/sorting.html

 

Sorting HOW TO

Author, Andrew Dalke and Raymond Hettinger,, Release, 0.1,. Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a...

docs.python.org

 

728x90

'Develop' 카테고리의 다른 글

Prompt Engineer  (0) 2023.03.12
[Python] list slicing replace  (0) 2023.03.05
[Python] input() vs sys.stdin.readline()  (0) 2023.03.01
Numpy array 생략없이 출력  (0) 2023.02.27
Comments