liveBook · Manning

Expression

As explained in Python Workout, Second Edition

An expression is Python syntax that evaluates to a value.

An expression is Python syntax that evaluates to a value. In comprehensions, it produces each output value while the iterable supplies inputs and an optional condition filters results. section 8.5

Choose a comprehension when creating a new object from returned values; choose a for loop when the goal is commands or side effects. In a dict comprehension, the expressions before and after the colon produce the key and value separately. section 8.19

[x*x      #1
 for x in range(10)       #2
 if x%2 == 0]     #3

Read the comprehension as transformation on line 1, iteration on line 2, and filtering on line 3. section 8.5

{ KEY : VALUE
  for ITEM in ITERABLE }

Use this template to identify the separate key and value expressions in a dictionary comprehension. section 8.19

How Python Workout, Second Edition covers it

How deep it goes
Explains expressions through comprehension structure and contrasts returned values with for-loop commands and side effects.
Examples
Uses squared even numbers, mapped word lengths, filtered words, and key-value dictionary construction as concrete examples.
What you can do after
Apply expressions to build transformed or filtered collections and select comprehensions or loops according to the desired result.
How it connects
Connects expressions with list comprehensions, dict comprehensions, iterables, map, filter, and for loops.

Also explained in

Compare how 11 books explain expression →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.