Home > OS >  I can't figure out how to loop twice in a Function to modify a list
I can't figure out how to loop twice in a Function to modify a list

Time:10-02

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)  # from this point i get this output for lst: [1,2,3,4,5,6,7,8,9,10,12,14,16,18,20]



even(lst,lst2)
print(lst) 


What I am trying to do here is take lst2 even numbers add them to lst, then modifying lst into all even numbers. Keep in mind I am trying to do all this in ONE function. if anyone can help me with this, it would be greatly appreciated. my desire output for lst is [2,4,6,8,10,12,14,16,18,20]

CodePudding user response:

You can use a slice assignment to replace a list with a modified list.

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

CodePudding user response:

Here's one way to do this. Traverse over lst in reverse order, so that we can also remove from the list while iterating over it.

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):
    # Add all elements of second list to the first list
    fn.extend(sn)

    for i in range(len(fn) -1, -1, -1):
        if fn[i] % 2 != 0:
            fn.pop(i)


even(lst, lst2)
print(lst)

CodePudding user response:

Here are my sugestion:

def even(fn,sn):
    union = fn   sn
    return [i for i in union if i % 2 == 0]

With the sum operation you can append all the list "sn" in the final of the list "fn". Then you can consctruct a list with only the even numbers.

I used a list comprehension that make a for loop in one line.

  • Related