0

This is my program :

def question_second_solution(nums):
    print("Even Numbers: ")
    even_nums = list(filter(lambda x: x%2==0,nums))
    print(even_nums)
    print("Odd Numbers: ")
    odd_nums = list(filter(lambda x: x%2!=0,nums))
    print(odd_nums)
    return nums

question_second_solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

So how can i get my output in below given format: Even Numbers: [2, 4, 6, 8, 10], Odd Numbers: [1, 3, 5, 7, 9]

Saurabh G
  • 19
  • 2
  • 8
  • Does this answer your question? [String formatting in Python 3](https://stackoverflow.com/questions/13945749/string-formatting-in-python-3) – G. Anderson Mar 31 '20 at 18:22
  • The print function implicitly outputs a newline after your string, but you can change this newline to any other character with the end argument. So if you don't want anything after the end of your string do: `print("Some text", end="")`. I would recommend Tom Ron's solution with an f-string though. – Moberg Mar 31 '20 at 18:29
  • Does this answer your question? [How to print without newline or space?](https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space) – Moberg Mar 31 '20 at 18:31

3 Answers3

3
print(f"Even numbers: {even_nums}, Odd numbers: {odd_nums}")
Tom Ron
  • 5,906
  • 3
  • 22
  • 38
1

If you want to just return the output as string then use below function. Here even_nums and odd_nums are arranged in a string and the value is returned.

def question_second_solution(nums):
    even_nums = list(filter(lambda x: x%2==0,nums))
    odd_nums = list(filter(lambda x: x%2!=0,nums))
    return "Even Numbers: {} Odd numbers: {}".format(even_nums, odd_nums)

If you want to return the even_nums and odd_nums values as list and reuse the values for further processing then you can return the values as tuple of lists. Like below:

return (even_nums, odd_nums)

Example of the second use case:

evens, odds = question_second_solution([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

print("Even numbers are: ", evens)
print("Odd numbers are: ", odds)

Hope this helps.

Adrish
  • 52
  • 1
  • 7
0

You can make it with a single line only.

def question_second_solution(nums):
    print(f"Even Numbers: %s, Odd numbers %s" % ([x for x in nums if x%2 == 0], [x for x in nums if x%2 != 0]))

String format with %s inside the string and inject the values with % after the string.

Moshe
  • 1
  • 1
  • Also, as I wrote it's better to use list comprehension inside of using a filter as you did and then convert it to list. https://blog.teamtreehouse.com/python-single-line-loops – Moshe Mar 31 '20 at 18:41