Home > Enterprise >  How can I let my code rearrange the list to put all even numbers at the front and odd numbers at the
How can I let my code rearrange the list to put all even numbers at the front and odd numbers at the

Time:11-18

So I'm trying to let my code return the list with all even numbers at the front and the odd numbers being appended at the end of the list. Here is my code so far...

s = [1,2,3,4,5,5]
def evenorodd(s):
    s = list(s)
    for i in range(len(s)-1):
        if s[i]%2 != 0:
            s.append(i)
    return s
print(evenorodd(s = [1,2,3,4,5,5]))

and this is the output that I get

[1, 2, 3, 4, 5, 5, 0, 2, 4]

but I want my output to be

[0,2,2,4,4,1,3,5,5]

What changes should I make

Order doesn't matter btw.. it's just that all even numbers must come before odd ones

CodePudding user response:

You could create two new lists in your function, one for even and one for odd numbers. Append each number to the correct list inside your loop. Once you're finished concatenate the lists together and return.

CodePudding user response:

You can use sorted to create your custom sort method for a list

s = [1,2,3,4,5,5,0,2]
s = sorted(s, key=lambda x: not x%2)
>>> [1, 3, 5, 5, 2, 4, 0, 2]

and if you want to sort the even number with themselves and the odd numbers too

s = [1,2,3,4,5,5,0,2]
s.sort()
s = sorted(s, key=lambda x: not x%2)
>>> [1, 3, 5, 5, 0, 2, 2, 4]

CodePudding user response:

You can append to two lists and concatenate them:

def evenorodd(s):
    evens = []
    odds = []
    for num in s:
        if num%2 == 0:
            evens.append(num)
        else:
            odds.append(num)
    return evens   odds

CodePudding user response:

How about doing it this way:

s = [1,2,3,4,5,5]

print([x for x in s if not x % 2]   [x for x in s if x % 2])
  • Related