[Tutor] Python program to remove first four even numbers from a list
Manprit Singh
manpritsinghece at gmail.com
Sun Oct 17 11:03:48 EDT 2021
Dear sir,
By writing this :
lst[:] = remove4even(lst) # here i am modify the existing list lst
But by doing this
lst = remove4even(lst) # Now variable lst is reassigned, so it is a
different object
Regards
Manprit Singh
On Sun, Oct 17, 2021 at 1:49 PM Alan Gauld via Tutor <tutor at python.org>
wrote:
> On 17/10/2021 02:09, Manprit Singh wrote:
> > Dear Sir,
> >
> > So finally I came up with this solution:
> > def remove4even(seq):
> > evencnt = 0
> > lx = []
> > for ele in seq:
> > if evencnt > 3 or ele%2 != 0:
> > lx.append(ele)
> > else:
> > evencnt += 1
> > return lx
> >
> > lst =[3, 6, 7, 5, 4, 7, 8, 9, 1, 8, 2, 5, 4]
> > print(remove4even(lst)) # gives the right answer as
> >
> > [3, 7, 5, 7, 9, 1, 2, 5, 4]
> >
> > and to bring these changes in the existing same list(lst), just doing
> this:
> > lst =[3, 6, 7, 5, 4, 7, 8, 9, 1, 8, 2, 5, 4]
> > lst[:] = remove4even(lst)
>
> You don't need the slice. Just assign the new list to lst
>
> lst = remove4even(lst)
>
> > Is there any other good way to achieve this ? I don't like changing
> > mutable data inside functions.
> What you have done is fine.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list