- sort
It sorts the list in-place, mutating its indexes and returning None.
a1 = [6, 3, 9]
print('a1:', a1)
a2 = a1.sort() # it sorts original(in-place)
print('-----after sorting-----')
print('a1:', a1)
print('a2:', a2)
>>>
a1: [6, 3, 9]
-----after sorting-----
a1: [3, 6, 9]
a2: None
- sorted
It returns a new sorted list, leaving the original list unchanged.
b1 = [6, 3, 9]
print('b1:', b1)
b2 = sorted(b1) # it creats new list and keep the original
print('-----after sorting-----')
print('b1:', b1)
print('b2:', b2)
>>>
b1: [6, 3, 9]
-----after sorting-----
b1: [6, 3, 9]
b2: [3, 6, 9]
- key
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),
]
sorted(student_tuples, key=lambda student: student[2]) # sort by age
>>>
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
sorted("This is a test string from Andrew".split(), key=str.casefold)
>>>
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
'Basic Python' 카테고리의 다른 글
str VS repr (0) | 2023.11.16 |
---|---|
getattr (0) | 2023.11.15 |
abspath, chdir, basename, os.path.join (0) | 2023.11.07 |
glob (0) | 2023.11.04 |
bytes VS bytearray (0) | 2023.10.30 |