Skip to content

Commit b31b645

Browse files
gh-84522: Add for-loop to apply-method-to-sequence FAQ (GH-94660)
(cherry picked from commit 97c493d) Co-authored-by: Samuel Sloniker <[email protected]>
1 parent edd92a1 commit b31b645

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

Doc/faq/programming.rst

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1279,13 +1279,25 @@ Or, you can use an extension that provides a matrix datatype; `NumPy
12791279
<https://numpy.org/>`_ is the best known.
12801280

12811281

1282-
How do I apply a method to a sequence of objects?
1283-
-------------------------------------------------
1282+
How do I apply a method or function to a sequence of objects?
1283+
-------------------------------------------------------------
12841284

1285-
Use a list comprehension::
1285+
To call a method or function and accumulate the return values is a list,
1286+
a :term:`list comprehension` is an elegant solution::
12861287

12871288
result = [obj.method() for obj in mylist]
12881289

1290+
result = [function(obj) for obj in mylist]
1291+
1292+
To just run the method or function without saving the return values,
1293+
a plain :keyword:`for` loop will suffice::
1294+
1295+
for obj in mylist:
1296+
obj.method()
1297+
1298+
for obj in mylist:
1299+
function(obj)
1300+
12891301
.. _faq-augmented-assignment-tuple-error:
12901302

12911303
Why does a_tuple[i] += ['item'] raise an exception when the addition works?

0 commit comments

Comments
 (0)