Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting input integers directly to a list

Tags:

python

To sort a series of numbers from the console, it is first appended into an myList and this myList is sorted using myList.sort()

n = int(input())
count = 0
myList = []

while count < n:
    i = int(input())
    myList.append(i)
    count += 1
    
myList.sort()
print(myList)

Is there a way in which as it gets added to the list it is directly and automatically placed in the correct order/index? I want to get rid of the sort() function and the unsorted myList, if possible.

like image 867
xb2107 Avatar asked Dec 13 '25 09:12

xb2107


2 Answers

You can use bisect.insort to insert into an already sorted list.

>>> from bisect import insort
>>> l = []
>>> insort(l, 5)
>>> l
[5]
>>> insort(l, 1)
>>> l
[1, 5]
>>> insort(l, 2)
>>> l
[1, 2, 5]

edit: If you don't require the list to be sorted after every insertion I'd just sort it once after the loop, though.

like image 167
timgeb Avatar answered Dec 15 '25 22:12

timgeb


Use SortedList from SortedContainers:

from sortedcontainers import SortedList

n = int(input())
count = 0
myList = SortedList()


while count < n:
    i = int(input())
    myList.add(i)
    count += 1

print(myList)

Output (example of a dummy run)

4
5
3
2
1
SortedList([1, 2, 3, 5])

It keeps the list sorted and the insertion time is O(logn) (see the documentation on .add)

Note

SortedContainers is a third-party library, needs to be install by doing:

pip install sortedcontainers
like image 26
Dani Mesejo Avatar answered Dec 15 '25 23:12

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!