You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
Reword the discussion on short ways to manipulate lists
- Remove emphasis on map and filter, in favor of generator expressions. - Move list comprehensions and generator expressions under "Short ways to manipulate lists" rather than "Filtering a list". - Add some examples.
* Possible side effects of modifying the original list
625
639
626
-
Python 2.x vs. 3.x
627
-
::::::::::::::::::
640
+
Never use a list comprehension just for its side effects.
628
641
629
-
Starting with Python 3.0, the:py:func:`filter` function returns an iterator instead of a list.
630
-
Wrap it in:py:func:`list` if you truly need a list.
642
+
**Bad**:
631
643
632
644
..code-block::python
633
645
634
-
list(filter(...))
646
+
[print(x)for xin seqeunce]
635
647
636
-
List comprehensions and generator expressions work the same in both 2.x and 3.x (except that comprehensions in 2.x "leak" variables into the enclosing namespace):
648
+
**Good**:
637
649
638
-
* Comprehensions create a new list object.
639
-
* Generators iterate over the original list.
650
+
..code-block::python
640
651
641
-
The:py:func:`filter` function:
652
+
for xin sequence:
653
+
print(x)
642
654
643
-
* in 2.x returns a list (use itertools.ifilter if you want an iterator)
644
-
* in 3.x returns an iterator
645
655
646
-
Lists vs. iterators
647
-
:::::::::::::::::::
656
+
Filtering a list
657
+
~~~~~~~~~~~~~~~~
658
+
659
+
**Bad**:
660
+
661
+
Never remove items from a list while you are iterating through it.
662
+
663
+
..code-block::python
664
+
665
+
# Filter elements greater than 4
666
+
a= [3,4,5]
667
+
for iin a:
668
+
if i>4:
669
+
a.remove(i)
670
+
671
+
Don't make multiple passes through the list.
672
+
673
+
..code-block::python
674
+
675
+
while iin a:
676
+
a.remove(i)
677
+
678
+
**Good**:
648
679
649
-
Creating anewlistrequires more work and uses more memory. If you a just going to loop through the new list, consider using an iterator instead.