From 0c74847971d4387094258082820fb3b06ba03511 Mon Sep 17 00:00:00 2001 From: Haolin Qin Date: Thu, 28 Aug 2025 11:10:56 +0800 Subject: [PATCH 1/2] gh-137818: Add multiple `if` statements example for list comprehensions --- Doc/tutorial/datastructures.rst | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst index cbe780e075baf5..7381f8f031676a 100644 --- a/Doc/tutorial/datastructures.rst +++ b/Doc/tutorial/datastructures.rst @@ -245,6 +245,18 @@ and it's equivalent to:: Note how the order of the :keyword:`for` and :keyword:`if` statements is the same in both these snippets. +For multiple :keyword:`!if` statements, like this:: + + >>> [x for x in range(10) if x % 2 if x % 3] + [1, 5, 7] + +This example is equivalent to:: + + >>> [x for x in range(10) if x % 2 and x % 3] + [1, 5, 7] + +Note the second :keyword:`!if` is replaced by :keyword:`!and`. + If the expression is a tuple (e.g. the ``(x, y)`` in the previous example), it must be parenthesized. :: From 1d8128aa0ae5270be807fd981e8d4f15fbab905a Mon Sep 17 00:00:00 2001 From: Haolin Qin Date: Sat, 1 Nov 2025 13:33:34 +0800 Subject: [PATCH 2/2] Update Doc/tutorial/datastructures.rst Co-authored-by: Carol Willing --- Doc/tutorial/datastructures.rst | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst index 7381f8f031676a..f25da6d58b911c 100644 --- a/Doc/tutorial/datastructures.rst +++ b/Doc/tutorial/datastructures.rst @@ -245,17 +245,32 @@ and it's equivalent to:: Note how the order of the :keyword:`for` and :keyword:`if` statements is the same in both these snippets. -For multiple :keyword:`!if` statements, like this:: +Looking at another example:: >>> [x for x in range(10) if x % 2 if x % 3] [1, 5, 7] This example is equivalent to:: - >>> [x for x in range(10) if x % 2 and x % 3] + >>> result = [] + >>> for x in range(10): + ... if x % 2: + ... if x % 3: + ... result.append(x) + ... + >>> result + [1, 5, 7] + +This example could be further simplified by combining the two :keyword:if statements:: + + >>> result = [] + >>> for x in range(10): + ... if x % 2 and if x % 3: + ... result.append(x) + ... + >>> result [1, 5, 7] -Note the second :keyword:`!if` is replaced by :keyword:`!and`. If the expression is a tuple (e.g. the ``(x, y)`` in the previous example), it must be parenthesized. ::