Im trying to make it print two lists for even and odd

im trying to make python print two list when inputted a list of even and odd number on being the odd numbers and another being the even but it always outputs the new list without even number and just 11 33 55


list = [11, 22, 33, 44, 55]


print ("Original list:")
print (list)


for i  in list:
	if(i%2 == 0):
	    list.remove(i)
for a in list :
    if not(a%2 == 0):
        print(a)

print (list)

I’ve copied your code into Even and Odd - Replit

First, I would encourage you not to call your list object “list” because it overrides the python built-in list object.

So you print the original list, and then the first for loop remove even numbers.
The second for loop print each element in that list (the if condition is a bit redundant because you already know that there are no even numbers in that list!)
Then you print the modified list.

There are many ways to just print a list containing the even numbers and a list containing the odd numbers, but I would use the filter higher order function:

my_list = [11, 22, 33, 44, 55]
even = list(filter(lambda x: x % 2 == 0, my_list))
odd = list(filter(lambda x: x % 2 != 0, my_list))

print(even)
print(odd)

Explanation:

The filter function accepts a function and an iterator.
even = list(filter(lambda x: x % 2 == 0, my_list)) means to filter out all the elements in my_list whose remainder after division by 2 is 0.
odd = list(filter(lambda x: x % 2 != 0, my_list)) means to filter out all the elements in my_list whose remainder after division by 2 is not 0.

Of course, you can do the same without the filter function by:

my_list = [11, 22, 33, 44, 55]

even = []
for num in my_list:
    if (num % 2 == 0):
        my_list.remove(num)
        even.append(num)

print(my_list)
print(even)

Hope that answers your question!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.