rem rem - 1 month ago 9
Python Question

Relocate all the evens

I'm supposed to remove any evens found in

info
and append them into the second argument,
house
. A reference to the list which received any evens must be returned. When no second argument is given, a list of all the relocated evens should be created and returned.

This is my code so far.

def relocate_even(info,house):
house=[]
new_list=[]
for x in info:
if x%2==0:
info.remove(x)
if len(house)>0:
house.append(x)
return house
if len(house)<=0:
new_list.append(x)
return new_list


I'm having trouble with when the house function is empty. I have code written for that but it gives me an error.

Answer

Don't modify iterables as you iterate over them. That is to say, don't change info in a for x in info: block. Instead create a new list and then set info equal to it. You can give an argument a default value, which allows for calls to not explicitly set that value.

def relocate_even(info, house=None):
    new_house = []
    new_info = []
    for x in info:
         if x%2:
             new_info.append(x)
         else:
             new_house.append(x)
    info[:] = new_info
    if house is None:
        return new_house
    else:
        house[:] = house + new_house
        return house