*Memo:
index() can get the index of the element matched to value
from the range as shown below:
*Memo:
- The 1st argument is
value
(Required-Type:Any). - Error occurs if
value
doesn’t exist.
v = range(5, 10)
print(*v)
# 5 6 7 8 9
print(v.index(7)) # 2
print(v.index(10)) # ValueError: 10 is not in range
count() can count the elements matched to value
in the range as shown below:
*Memo:
- The 1st argument is
value
(Required-Type:Any):
v = range(5, 10)
print(*v)
# 5 6 7 8 9
print(v.count(7)) # 1
print(v.count(10)) # 0
sorted() can convert a range to a list, then sort the list as shown below:
*Memo:
- The 1st argument is
iterable
(Required-Type:Iterable): - The 2nd argument is
key
(Optional-Default:None
-Type:Callable or NoneType). - The 3rd argument is
reverse
(Optional-Default:False
-Type:bool
) to reverse the list. -
sorted()
creates a copy:- Be careful,
sorted()
does shallow copy instead of deep copy as my issue.
- Be careful,
v = range(-3, 3)
print(*v)
# -3 -2 -1 0 1 2
print(sorted(v))
print(sorted(v, key=None, reverse=False))
# [-3, -2, -1, 0, 1, 2]
print(sorted(v, reverse=True))
# [2, 1, 0, -1, -2, -3]
print(sorted(v, key=abs))
# [0, -1, 1, -2, 2, -3]
print(sorted(v, key=abs, reverse=True))
# [-3, -2, 2, -1, 1, 0]
reversed() can return the iterator which has the reversed elements of a range as shown below:
*Memo:
- The 1st argument is
seq
(Required-Type:Sequence):
v = range(5)
print(*v)
# 0 1 2 3 4
print(reversed(v))
#
print(*reversed(v))
# 4 3 2 1 0