Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of results coming from a list comprehension guaranteed?

When using a list comprehension, is the order of the new list guaranteed in any way? As a contrived example, is the following behavior guaranteed by the definition of a list comprehension:

>> a = [x for x in [1,2,3]] >> a [1, 2, 3] 

Equally, is the following equality guaranteed:

>> lroot = [1, 2, 3] >> la = [x for x in lroot] >> lb = [] >> for x in lroot:      lb.append(x) >> lb == la True 

Specifically, it's the ordering I'm interested in here.

like image 699
Dan Avatar asked Aug 17 '09 04:08

Dan


People also ask

What does a list comprehension return?

List comprehensions are used for creating new lists from other iterables. As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.

What is list comprehension what is its advantage?

One main benefit of using a list comprehension in Python is that it's a single tool that you can use in many different situations. In addition to standard list creation, list comprehensions can also be used for mapping and filtering. You don't have to use a different approach for each scenario.

What makes a list comprehension different from a generator?

So what's the difference between Generator Expressions and List Comprehensions? The generator yields one item at a time and generates item only when in demand. Whereas, in a list comprehension, Python reserves memory for the whole list.

Is list comprehension always faster than for loop?

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.


1 Answers

Yes, the list comprehension preserves the order of the original iterable (if there is one). If the original iterable is ordered (list, tuple, file, etc.), that's the order you'll get in the result. If your iterable is unordered (set, dict, etc.), there are no guarantees about the order of the items.

like image 151
Arkady Avatar answered Oct 12 '22 15:10

Arkady