1

Can we create sorted list while creation of list itself?

Or

Is there any other data structure that can place values in sorted order, at creation time?

list = []
list.append("cde")
list.append("abc")
list.append("xyz")  # append element in sorted order itself 

I am familiar with

list.sort()  #or
list = sorted(list)
Nikhil Rupanawar
  • 4,061
  • 10
  • 35
  • 51
  • See http://stackoverflow.com/questions/5527630/is-there-a-standard-python-data-structure-that-keeps-thing-in-sorted-order – alecxe Aug 22 '13 at 08:22

4 Answers4

2

You can use bisect to perform ordered insertions within a sequence.

bisect.bisect_left(a, x, lo=0, hi=len(a))

Locate the insertion point for x in a to maintain sorted order. [...] The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted.

Community
  • 1
  • 1
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0

You can use OrderedDict to create ordered dictionaries. You can import OrderedDict from here from collections import OrderedDict

sandeep
  • 3,061
  • 11
  • 35
  • 54
0

you can use heapq methods

>>> list = []
>>> import heapq
>>> heapq.heappush(list, "cde")
>>> heapq.heappush(list, "abc")
>>> heapq.heappush(list, "xyz")
>>> heapq.nsmallest(3, list)
['abc', 'cde', 'xyz']

It's not actually ordered, but you could perform ordered operations you need

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
0

I found this is useful,

class SList(list):
    def append(self, data):
        super(SList, self).append(data)
        super(SList, self).sort()


slist = SList()
slist.append("cde")
slist.append("abc")
slist.append("xyz")
print slist

In same way we can override other methods also to keep list state sorted

Nikhil Rupanawar
  • 4,061
  • 10
  • 35
  • 51