Skip to content Skip to sidebar Skip to footer

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 wan

Solution 1:

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)

Solution 2:

Edited:

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

Solution 3:

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)

Post a Comment for "How To Insert Elements Of A List Into Another List Depending On Date Value?"