zip as iterator and bad/good practices
sohcahtoa82 at gmail.com
sohcahtoa82 at gmail.com
Fri Jun 12 20:02:24 EDT 2015
On Friday, June 12, 2015 at 4:44:08 PM UTC-7, Terry Reedy wrote:
> On 6/12/2015 4:34 PM, Laura Creighton wrote:
> > The real problem is removing things from lists when you are iterating
> > over them, not adding things to the end of lists.
>
> One needs to iterate backwards.
>
> >>> ints = [0, 1, 2, 2, 1, 4, 6, 5, 5]
>
> >>> for i in range(len(ints)-1, -1, -1):
> if ints[i] % 2:
> del ints[i]
>
> >>> ints
> [0, 2, 2, 4, 6]
>
> But using a list comp and, if necessary, copying the result back into
> the original list is much easier.
>
> >>> ints = [0, 1, 2, 2, 1, 4, 6, 5, 5]
> >>> ints[:] = [i for i in ints if not i % 2]
> >>> ints
> [0, 2, 2, 4, 6]
>
>
> --
> Terry Jan Reedy
On the second line of your final solution, is there any reason you're using `ints[:]` rather than just `ints`?
More information about the Python-list
mailing list