Ad

How To Sort First Half In Ascending And Second Half In Descending Order In Python?

- 1 answer

I have a python list [1,2,3,4,5] I have to print [1,2,3,4,5,5,4,3,2,1].

Please suggest how to do in loop(while or for)

Ad

Answer

Using a for loop:

>>> l = [1, 2, 3, 4, 5]
>>> res = []
>>> for e in reversed(l):
...     res.append(e)
...     res.insert(0, e)
>>> res
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]

In case the list is not sorted, instead of reversed use sorted with the reverse flag set to True

>>> l = [4, 3, 1, 5, 2]
>>> res = []
>>> for e in sorted(l, reverse=True):
...     res.append(e)
...     res.insert(0, e)
... 
>>> res
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]

And, for a more efficient version I would suggest using iterators:

>>> import itertools
>>> l = sorted([4, 3, 1, 5, 2])
>>> res = list(itertools.chain(l, reversed(l)))
>>> res
[1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
Ad
source: stackoverflow.com
Ad