Joshua Bradley
Joshua Bradley

Reputation: 199

How can I let my code rearrange the list to put all even numbers at the front and odd numbers at the back?

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

Upvotes: 0

Views: 431

Answers (3)

AlexisG
AlexisG

Reputation: 2484

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]

Upvotes: 1

Kroshtan
Kroshtan

Reputation: 677

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

Upvotes: 0

Conor
Conor

Reputation: 1088

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.

Upvotes: 1

Related Questions