Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I sort elements of array in function?

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 array
But result is

None
None

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading