[Tutor] Python program to remove first four even numbers from a list

Alan Gauld alan.gauld at yahoo.co.uk
Sun Oct 17 04:19:06 EDT 2021


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




More information about the Tutor mailing list