*Memos:
- My post explains a list and the list with indexing.
- My post explains the list with slicing and copy.
- My post explains the useful functions for a list (1).
- My post explains variable assignment.
- My post explains shallow copy and deep copy.
You can use sort() to sort a list as shown below:
*Memos:
- The 1st argument is
key
(Optional-Default:None
) for a function. - The 2nd argument is
reverse
(Optional-Default:False
) to reverse a list. -
sort()
doesn't create a copy different from sorted().
v = [-4, 1, 5, 3, -2]
v.sort()
print(v) # [-4, -2, 1, 3, 5]
v.sort(reverse=True)
print(v) # [5, 3, 1, -2, -4]
v.sort(key=abs)
print(v)
# [1, -2, 3, -4, 5]
v.sort(key=abs, reverse=True)
print(v)
# [5, -4, 3, -2, 1]
v = ["apple", "Banana", "Kiwi", "cherry"]
# Case sensitive sort
v.sort()
print(v) # ['Banana', 'Kiwi', 'apple', 'cherry']
# Case insensitive sort
v.sort(key=str.upper)
v.sort(key=str.lower)
print(v) # ['apple', 'Banana', 'cherry', 'Kiwi']
# Sort by the length of a word
v.sort(key=len)
print(v) # ['Kiwi', 'apple', 'Banana', 'cherry']
You can use sorted() to sort a list as shown below:
*Memos:
- The 1st argument is
iterable
(Required) for an iterable. *Don't useiterable=
. - The 2nd argument is
key
(Optional-Default:None
) for a function. - The 3rd argument is
reverse
(Optional-Default:False
) to reverse a list. -
sorted()
creates a copy different from sort(). *Be careful,sorted()
does shallow copy instead of deep copy as my issue.
v = [-4, 1, 5, 3, -2]
print(sorted(v))
# [-4, -2, 1, 3, 5]
print(sorted(v, reverse=True))
# [5, 3, 1, -2, -4]
print(sorted(v, key=abs))
# [1, -2, 3, -4, 5]
print(sorted(v, key=abs, reverse=True))
# [5, -4, 3, -2, 1]
v = ["apple", "Banana", "Kiwi", "cherry"]
# Case sensitive sort
print(sorted(v))
# ['Banana', 'Kiwi', 'apple', 'cherry']
# Case insensitive sort
print(sorted(v, key=str.upper))
print(sorted(v, key=str.lower))
# ['apple', 'Banana', 'cherry', 'Kiwi']
# Sort by the length of a word
print(sorted(v, key=len))
# ['Kiwi', 'apple', 'Banana', 'cherry']
You can use reverse() to reverse a list as shown below. *There are no arguments:
v = [-4, 1, 5, 3, -2]
v.reverse()
print(v) # [-2, 3, 5, 1, -4]
v = ["apple", "Banana", "Kiwi", "cherry"]
v.reverse()
print(v) # ['cherry', 'Kiwi', 'Banana', 'apple']
You can use reversed() to reverse a list as shown below:
*Memos:
- The 1st argument is
seq
(Required) for an iterable. - *Don't use
seq=
:
v = [-4, 1, 5, 3, -2]
print(list(reversed(v))) # [-2, 3, 5, 1, -4]
v = ["apple", "Banana", "Kiwi", "cherry"]
print(list(reversed(v))) # ['cherry', 'Kiwi', 'Banana', 'apple']
Top comments (0)