Search code examples
listpython-3.xadditionmultiplication

Python3 multiply and add in a list.


got stuck in a exercise and could need som help!

Exercise: Create a function that takes the list:

[123, 4, 125, 69, 155]

as argument. The function should multiply all even numbers by 1 and add 6 to all odd numbers. Answer with the modified list sorted in numerical order, descending.

my code so far is.

list1 = [123, 4, 125, 69, 155]

def multi():
    for num in list1:
        if num % 2 == 0:
            num * 1
        else:
            num + 6
        return list1

In the answer i put `def multi():

the answer i get is

[123, 4, 125, 69, 155] <class 'list'>

and the correct answer is [161,131,129,75,4]

could anyone please point me in the right way?

Thank you.


Solution

  • You are modify the for loop variable num itself and not the original list value Code below should do the job

    list1 = [123, 4, 125, 69, 155]
    def multi():
        for i,num in enumerate(list1):
            if num % 2 == 0:
                num *= 1
            else:
                num += 6
            list1[i] = num # modify list value 
        return sorted(list1)[::-1] # this do sorting then reverse from large to small