@@ -581,6 +581,32 @@ provide a powerful, concise way to work with lists. Also, the :py:func:`map` and
581581:py:func: `filter ` functions can perform operations on lists using a different,
582582more concise syntax.
583583
584+ Starting with Python 3.0, the :py:func: `map ` and :py:func: `filter `
585+ functions return an iterator instead of a list. If you really need a list, you
586+ should wrap these functions in :py: func`list` like so
587+
588+ .. code-block :: python
589+
590+ list (map (... ))
591+ list (filter (... ))
592+
593+ Filtering a list
594+ ~~~~~~~~~~~~~~~~
595+
596+ **Very Bad **:
597+
598+ Never remove items from a list that you are iterating over.
599+ Python will lose track of its current position.
600+
601+ .. code-block :: python
602+
603+ # Filter elements greater than 4
604+ a = [3 , 4 , 5 ]
605+ for i in a:
606+ if i > 4 :
607+ a.remove(i)
608+
609+
584610 **Bad **:
585611
586612.. code-block :: python
@@ -598,9 +624,13 @@ more concise syntax.
598624
599625 a = [3 , 4 , 5 ]
600626 b = [i for i in a if i > 4 ]
601- # Or:
627+ # Or (Python 2.x) :
602628 b = filter (lambda x : x > 4 , a)
603-
629+ # Or (Python 3.x)
630+ b = list (filter (lambda x : x > 4 , a))
631+
632+ Modifying the values in a list
633+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
604634**Bad **:
605635
606636.. code-block :: python
@@ -616,8 +646,25 @@ more concise syntax.
616646
617647 a = [3 , 4 , 5 ]
618648 a = [i + 3 for i in a]
619- # Or:
649+ # Or (Python 2.x) :
620650 a = map (lambda i : i + 3 , a)
651+ # Or (Python 3.x)
652+ a = list (map (lambda i : i + 3 , a))
653+
654+ **Best **:
655+
656+ Creating a new list instead of modifying the original list will prevent
657+ unexpected side-effects.
658+
659+ .. code-block :: python
660+
661+ a = [3 , 4 , 5 ]
662+ b = [i + 3 for i in a]
663+ # Or (Python 2.x):
664+ b = map (lambda i : i + 3 , a)
665+ # Or (Python 3.x)
666+ b = list (map (lambda i : i + 3 , a))
667+
621668
622669 Use :py:func: `enumerate ` keep a count of your place in the list.
623670
0 commit comments