I have a list of homes :
list1 = [home1, home2, home3, home4]
and I have another list of specific homes:
list2 = [ home6, home7, home8, home10]
Every home has a field date .I want to insert List2 into list1 depending on
home.date
For example if home7.date < home1.date, so home7 will be inserted into list1 before home1
I tried to use two for loops but it seems to be very slow and there are many calculations done by the CPU
for el in list1:
for elt2 in list2:
if el.date > elt2.date:
list1.insert((list1.index(el)),elt2)
PS : some dates are not set so they have a None value and I don't want to change the index of corresponded home in list1
Any ideas ?
First thing first: modifying a list (or dict, set etc) while iterating over it is usually a very bad idea.
In your case, the simplest solution is probably to just merge the two lists first then sort the list using the key callback:
list1.extend(list2)
list1.sort(key=lambda x: x.date)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With