Home > OS >  Tring to figure out how to iterate a list twice in a One function
Tring to figure out how to iterate a list twice in a One function

Time:10-03

I am trying to figure out how to iterate over fn to modify the list again with only even numbers, AFTER appending. The desire result is [2,4,6,8,10,12,14,16,18,20] is this possible? I do not want to add fn sn or lst lst2. I want to continue over this specific function.

lst = [1,2,3,4,5,6,7,8,9,10]
lst2 =[11,12,13,14,15,16,17,18,19,20]


def even(fn,sn):
    for i in sn:
        if i %2 ==0:
            fn.append(i)
        

even(lst,lst2)
print(lst) # output [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20]

I know there are more efficient and pythonic ways like this example:

example 1:

def even2(fn,sn):
    fn[:] = [x for x in fn   sn if x % 2 == 0]

example 2:

def even(fn, sn):
    fn.extend(sn)
    fn[:] = [x for x in fn if x % 2 == 0]
def even(fn,sn):
    for i in sn:
        if i %2 ==0:
            fn.append(i)
            fn = list(filter(lambda x: x %2 == 0, fn))

the last code block is what i tried and failed with

CodePudding user response:

You don't need to rebuild the entire list; just extend it with the desired extra elements.

>>> lst = [1,2,3,4,5,6,7,8,9,10]
>>> lst2 =[11,12,13,14,15,16,17,18,19,20]
>>> def even(fn, sn):
...     fn.extend(i for i in sn if i % 2 == 0)
...
>>> even(lst, lst2)
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20]

In the above expression i for i... is a generator expression that allows extend to iterate over all of the i elements without storing them in a separate list first.

CodePudding user response:

Does this meet your requirements? Pulling lst into the even() func as a global.

lst = [1,2,3,4,5,6,7,8,9,10]
lst2 =[11,12,13,14,15,16,17,18,19,20]
def even(fn, sn):
    global lst
    lst = [x for x in (fn   sn) if x % 2 == 0]

even(lst,lst2)
print(lst)
  • Related