Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does filter preserve list ordering?

Tags:

python

filter

Say you call the "filter" function on a list, and you use this to find all elements that satisfy a certain property. Are the elements in the output list guaranteed to be in the same order that they were in the input list?

like image 831
Jessica Avatar asked Oct 25 '14 20:10

Jessica


People also ask

Does filter keep order?

Yes, the . filter() method returns a new array, without the filtered elements in the same order as initially. The order of the elements is one of the main feature of a array.

Does filter change the order of array?

JavaScript Array filter() The filter() method does not execute the function for empty elements. The filter() method does not change the original array.

Does a list keep its order?

Yes. A List, by definition, always preserves the order of the elements. This is true not only of ArrayList, but LinkedList, Vector, and any other class that implements the java.

Is filter or list comprehension faster?

Actually, list comprehension is much clearer and faster than the filter+lambda combination, but you can use whichever you find easier.


1 Answers

The simple answer is yes. Lists are ordered iterables, and the filter generator reads each item in, one at a time in that order. Therefore, it will yield output in order.

>>> example = list(range(10))
>>> list(filter(lambda n: n % 2, example))
[1, 3, 5, 7, 9]
like image 93
anon582847382 Avatar answered Sep 25 '22 21:09

anon582847382