Python 101 : List and tuple comprehension

list is an aggregate of elements enclosed in brackets.

list comprehension is constituted of:
  • an expression. 
  • a for loop. 
  • an if clause within the loop.
The line : [expr for expr in list if "condition is true"] , means that, in the list, we need expr for each expr in list if the condition is true.

Below is a simple example:

The above is the same as the below code:

Below is a tuple example:

Is equivalent to:


Leave as a comment: