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

Manprit Singh manpritsinghece at gmail.com
Sat Oct 16 21:09:34 EDT 2021


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)
print(lst)    will give the right answer [3, 7, 5, 7, 9, 1, 2, 5, 4]

Is there any other  good way to achieve this ? I don't like changing
mutable data inside functions.

Regards

Manprit Singh


On Sun, Oct 17, 2021 at 4:23 AM Alan Gauld <learn2program at gmail.com> wrote:

>
> On 16/10/2021 17:55, Manprit Singh wrote:
> > lst =[3, 6, 7, 5, 4, 7, 8, 9, 1, 8, 2, 5, 4]
>
> > Secondarily this example can be done with list comprehensions ?
>
> Just for laughs...
>
> >>> count = 0
> >>> [n for n in lst if n%2 or ((count := count+1) > 4)]
> [3, 7, 5, 7, 9, 1, 2, 5, 4]
>
> But I probably wouldn't recommend it. Explicit is better in this case I
> think.
>
> Alan G
>
>
> _______________________________________________
> 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