How can I sort elements of list in function?

Question:

Why I got: None
None

def odd_even(*number):
    even = []
    odd = []
    for i in number:
        if i % 2 == 0:
            even.append(i)
        else:
            odd.append(i)
    print(even.sort())
    print(odd.sort())
odd_even(1,5,7,8,4,3,26,59,48,7,5,45)

I just tried sorting elements of list
But result is

None
None
Asked By: Necip Arda

||

Answers:

you can use the sorted() function which returns a new sorted list and leaves the original list unaffected:

def odd_even(*number):
    even = []
    odd = []
    for i in number:
        if i % 2 == 0:
            even.append(i)
        else:
            odd.append(i)
    print(sorted(even))
    print(sorted(odd))

odd_even(1,5,7,8,4,3,26,59,48,7,5,45)
#output
#[4, 8, 26, 48]
#[1, 3, 5, 5, 7, 7, 45, 59]

Other Method (Fix your solution):

If you want to print the sorted lists, you should sort the lists first and then print them:

def odd_even(*number):
    even = []
    odd = []
    for i in number:
        if i % 2 == 0:
            even.append(i)
        else:
            odd.append(i)
    even.sort()
    odd.sort()
    print(even)
    print(odd)

odd_even(1,5,7,8,4,3,26,59,48,7,5,45)

Other Methode:

In this code, we use a list comprehension to filter out even and odd numbers from number and sort them directly as they are created. Then we print the even and odd lists which are already sorted.

def odd_even(*number):
    even = sorted([i for i in number if i % 2 == 0])
    odd = sorted([i for i in number if i % 2 != 0])
    print(even)
    print(odd)
odd_even(1,5,7,8,4,3,26,59,48,7,5,45)
Answered By: XMehdi01

As noted, list.sort has the effect of sorting the existing list. As such, in keeping with Python conventions, it does not return the list, but rather None.

This is why you’re seeing what you are. You can either use list.sort in a separate step before printing them, or use sorted. E.g. print(sorted(even)).

You might also sort the original list before separating into evens and odds. Doing this will ensure both resulting lists are sorted. However, this is likely to be less performant as sorting two smaller lists is less costly than sorting one larger list.

Answered By: Chris
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.