File tree Expand file tree Collapse file tree 1 file changed +12
-4
lines changed Expand file tree Collapse file tree 1 file changed +12
-4
lines changed Original file line number Diff line number Diff line change @@ -586,8 +586,7 @@ Filtering a list
586
586
587
587
**Bad **:
588
588
589
- Never remove items from list while you are iterating through it.
590
- Python will lose track of its current position.
589
+ Never remove items from a list while you are iterating through it.
591
590
592
591
.. code-block :: python
593
592
@@ -597,8 +596,17 @@ Python will lose track of its current position.
597
596
if i > 4 :
598
597
a.remove(i)
599
598
599
+ Don't make multiple passes through the list.
600
+
601
+ .. code-block :: python
602
+
603
+ while i in a:
604
+ a.remove(i)
605
+
606
+ **Good **:
607
+
600
608
Python has a few standard ways of filtering lists.
601
- You will need to consider
609
+ The approach you use depends on
602
610
603
611
* Python 2.x vs. 3.x
604
612
* Lists vs. iterators
@@ -608,7 +616,7 @@ Python 2.x vs. 3.x
608
616
::::::::::::::::::
609
617
610
618
Starting with Python 3.0, the :py:func: `filter ` function returns an iterator instead of a list.
611
- If you really need a list, you should wrap it in :py:func: `list ` like so
619
+ Wrap it in :py:func: `list ` if you truly need a list.
612
620
613
621
.. code-block :: python
614
622
You can’t perform that action at this time.
0 commit comments