pietà
pietà

Reputation: 770

How to insert elements of a list into another list depending on date value?

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 ?

Upvotes: 3

Views: 335

Answers (3)

rachid
rachid

Reputation: 2496

To return a new sorted list, you should use the sorted() built-in function:

sorted_list = sorted(list1 + list2, key=lambda x: x.date, reverse=True)

Upvotes: 2

ShreyasG
ShreyasG

Reputation: 806

Edited:

list3 = (list1 + list2)
list3.sort(key = lambda x: x.date)

Upvotes: 2

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

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)

Upvotes: 8

Related Questions