[Python-checkins] gh-84522: Add for-loop to apply-method-to-sequence FAQ (#94660)

rhettinger webhook-mailer at python.org
Thu Nov 10 23:16:24 EST 2022


https://github.com/python/cpython/commit/97c493dd3543c7c3bb5319587c162f46271d4c5d
commit: 97c493dd3543c7c3bb5319587c162f46271d4c5d
branch: main
author: Samuel Sloniker <sam at kj7rrv.com>
committer: rhettinger <rhettinger at users.noreply.github.com>
date: 2022-11-10T22:16:16-06:00
summary:

gh-84522: Add for-loop to apply-method-to-sequence FAQ (#94660)

files:
M Doc/faq/programming.rst

diff --git a/Doc/faq/programming.rst b/Doc/faq/programming.rst
index f3c5b0f76494..584d33e9622e 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?



More information about the Python-checkins mailing list