Basic Python | Comprehension Types


List Comprehensions

List comprehensions are simply a way to compress a list-building for-loop into a single short, readable line. For example, here is a loop that constructs a list of the first 12 square integers with for loop and list comprehension
Conditionals on the Value
If you've programmed in C, you might be familiar with the single-line conditional enabled by the ? operator:
int absval = (val < 0) ? -val : val
Python has something very similar to this, which is most often used within list comprehensions, lambda functions, and other places where a simple expression is desired. Shown is a simple logic to extract the odd and even number given in the range.  
      val = -10; val if val >= 0 else -val
Once you understand the dynamics of list comprehensions, it's straightforward to move on to other types of comprehensions. The syntax is largely the same; the only difference is the type of bracket you use.For example, with curly braces you can create a set with a Set comprehension. A  set is a collection that contains no duplicates. The set comprehension respects this rule, and eliminates any duplicate entries.
A Generator expression is essentially a list comprehension in which elements are generated as-needed rather than all at-once. Printing the generator expression does not print the contents; one way to print the contents of a generator expression is to pass it to the list constructor. 
When you create a list, you are actually building a collection of values, and there is some memory cost associated with that. When you create a generator, you are not building a collection of values, but a recipe for producing those values. The difference is that a generator expression does not actually compute the values until they are needed. This not only leads to memory efficiency, but to computational efficiency as well! This also means that while the size of a list is limited by available memory, the size of a generator expression is unlimited!

No comments:

Post a Comment

Note: only a member of this blog may post a comment.