You haven't answered my question about how you want to "null" dates handled—by which I assume you mean values of None
—so the following may process these correctly.
You did say "but I need obj with null values to be in their indexes" in a comment under a different answer, so I implemented something that does that, otherwise preserving the original order when inserting elements from the second list which can be in any order...and it doesn't seem to run terribly slow (or hang).
import datetime
class Object(object):
def __init__(self, date_string=None):
self.date = (date_string if date_string is None else
datetime.datetime.strptime(date_string, "%Y%m%d"))
def __repr__(self):
return '{}({!r})'.format(self.__class__.__name__,
self.date.strftime("%Y%m%d") if self.date
else None)
obj1 = Object('20171001')
obj2 = Object('20171002')
obj3 = Object(None)
obj4 = Object('20171004')
obj5 = Object('20171005')
obj6 = Object('20171006')
obj7 = Object('20171007')
obj8 = Object('20171008')
obj9 = Object('20171009')
l1 = [obj1, obj2, obj3, obj4, obj5]
l2 = [obj9, obj6, obj7, obj8]
print('Before:')
print(l1)
print(l2)
for elem2 in l2:
for i, elem1 in enumerate(l1):
if elem1.date and elem2.date < elem1.date:
l1.insert(i, elem2)
break
else:
l1.append(elem2)
print('After:')
print(l1)
Output:
Before:
[Object('20171001'), Object('20171002'), Object(None), Object('20171004'), Object('20171005')]
[Object('20171009'), Object('20171006'), Object('20171007'), Object('20171008')]
After:
[Object('20171001'), Object('20171002'), Object(None), Object('20171004'), Object('20171005'), Object('20171006'), Object('20171007'), Object('20171008'), Object('20171009')]
`