Best way to insert sorted in a list

Steve D'Aprano steve+python at pearwood.info
Fri Sep 8 15:00:25 EDT 2017


On Sat, 9 Sep 2017 04:39 am, logonveera at gmail.com wrote:

> On Saturday, June 18, 2011 at 2:23:10 AM UTC+5:30, SherjilOzair wrote:
.......................^^^^^^

You're replying to something six years old. Its doubtful the original poster is
still reading.


>> What has the community to say about this ? What is the best (fastest)
>> way to insert sorted in a list ?
> 
> a = []
> num = int(input('How many numbers: '))
> for n in range(num):
>     numbers = int(input('Enter values:'))
>     a.append(numbers)
> 
> b = sorted(a)
> print(b)
> c = int(input("enter value:"))
> for i in range(len(b)):
>     if b[i] > c:
>         index = i
>         break
> d = b[:i] + [c] + b[i:]
> print(d)

Doing a linear search, followed by slicing and list concatenation, is not likely
to be the fastest method. If you think it is fast, that's because you have only
tested it on small lists. Try a list with (say) a million items.

Probably the best way is to use the bisect module to insert into a sorted list.
Or append to the end, then sort in place. Python's sort is *very* efficient
with almost sorted data.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list