Python Sorted Reverse

n_1
=
{
6
:
‘Six’
,
7
:
‘Seven’
,
8
:
‘Eight’
}
asc_nums1
=
sorted
(
n_1
)
dsc_nums1
=
sorted
(
n_1
,
reverse
=
True
)
print
(
“Here is Ascending List: ”
,
asc_nums1
)
print
(
“Here isDescending List: ”
,
dsc_nums1
)
n_1
=
(
‘four’
,
‘five’
,
‘six’
,
‘seven’
)
asc1_nums
=
sorted
(
n_1
,
key
=
len
)
dsc1_nums
=
sorted
(
n_1
,
key
=
len
,
reverse
=
True
)
print
(
“Here is Ascending List: ”
,
asc1_nums
)
print
(
“Here is Descending List: ”
,
dsc1_nums
)


Question:

Given a list, a, which includes the elements ‘L’, ‘N’, and ‘D’, I am attempting to obtain a new list, b, where the order of elements is reversed. My current attempt involves the following method:

a = ['L', 'N', 'D']
b = sorted(a, reverse=True)

But the output is

b= ['N', 'L', 'D']

Where do I make a mistake?


Solution 1:

Using

sorted

is your mistake as it rearranges the list by elements and disregards their original positions. Therefore, it is recommended to use an alternative method.

b = a[::-1]

Reverse order can be applied to the list

a

. Additionally, there is the option to utilize this method.

b = list(reversed(a))

Whilst the initial version presents a quicker speed.


Solution 2:


One can sort using the sorted() function by specifying the key on which the sorting is to be performed, which could be an index.

b = sorted(a, key=a.index, reverse=True)


Solution 3:

You can also reverse in place:

>>> a = ['L', 'N', 'D']
>>> a.reverse()
>>> a
['D', 'N', 'L']

Kindly take note that the list undergoes modification and not creation of a new one.


Solution 4:

To perform a reverse sort in-place, an alternative approach is as follows:

a.sort(reverse=True)

Frequently Asked Questions