summaryrefslogtreecommitdiffstats
path: root/Doc/faq
diff options
context:
space:
mode:
authorSamuel Sloniker <sam@kj7rrv.com>2022-11-11 04:16:16 (GMT)
committerGitHub <noreply@github.com>2022-11-11 04:16:16 (GMT)
commit97c493dd3543c7c3bb5319587c162f46271d4c5d (patch)
treef63865b26fa2cb9c0da63499353025c619c60a1b /Doc/faq
parentd26ee8a0a552de111b8245ef0de63e3f3f535d9f (diff)
downloadcpython-97c493dd3543c7c3bb5319587c162f46271d4c5d.zip
cpython-97c493dd3543c7c3bb5319587c162f46271d4c5d.tar.gz
cpython-97c493dd3543c7c3bb5319587c162f46271d4c5d.tar.bz2
gh-84522: Add for-loop to apply-method-to-sequence FAQ (#94660)
Diffstat (limited to 'Doc/faq')
-rw-r--r--Doc/faq/programming.rst18
1 files changed, 15 insertions, 3 deletions
diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst
index f3c5b0f..584d33e 100644
--- a/Doc/faq/programming.rst
+++ b/Doc/faq/programming.rst
@@ -1279,13 +1279,25 @@ Or, you can use an extension that provides a matrix datatype; `NumPy
<https://numpy.org/>`_ is the best known.
-How do I apply a method to a sequence of objects?
--------------------------------------------------
+How do I apply a method or function to a sequence of objects?
+-------------------------------------------------------------
-Use a list comprehension::
+To call a method or function and accumulate the return values is a list,
+a :term:`list comprehension` is an elegant solution::
result = [obj.method() for obj in mylist]
+ result = [function(obj) for obj in mylist]
+
+To just run the method or function without saving the return values,
+a plain :keyword:`for` loop will suffice::
+
+ for obj in mylist:
+ obj.method()
+
+ for obj in mylist:
+ function(obj)
+
.. _faq-augmented-assignment-tuple-error:
Why does a_tuple[i] += ['item'] raise an exception when the addition works?