0

The function is supposed to take a list of numbers, and then generate two new lists separating even and uneven numbers in each one.

def separate(list):
    evenList = []
    unevenList = []
    for e in list:
        if e % 2 == 0:
            evenList.append(e)
        elif e % 1 == 0:
            unevenList.append(e)

    print(f"The even list is ", evenList)
    print(f"The uneven list is ", unevenList)        

I notice when my argument ends in an even number, it appends everything into the even list, and same if it ends in an uneven number with the uneven list. I just need a way to iterate based on the conditional, and append only those number that meet the criteria to each new list.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Shize
  • 43
  • 5
  • 1
    it should just be ```else:``` not ```elif e % 1 == 0:``` – Nin17 Apr 27 '22 at 23:34
  • Does this answer your question? [Check if a number is odd or even in python](https://stackoverflow.com/questions/21837208/check-if-a-number-is-odd-or-even-in-python) – mkrieger1 Apr 27 '22 at 23:35
  • Your problem is not "a way to iterate based on the conditional, and append only those number that meet the criteria to each new list". You already did that, you just used the wrong criteria. – mkrieger1 Apr 27 '22 at 23:37
  • I checked the link, but that doesn't answer my question, my problem isn't how to check if something is even or uneven. My problem is finding a way to access the iterable in a way that only "touches" even or uneven numbers. Or rather that while iterating I find a way to make it iterate only those specific numbers. The conditional doesn't allow me to access only even or uneven numbers, even though the program is successfully checking every element and seeing if it's even or uneven. But the iteration of for, arrives at the very last element, checks if its even or uneven and bundles up everything – Shize Apr 28 '22 at 01:21

1 Answers1

1

You can do it with two list comprehensions (also, you shouldn't overwrite the builtin python list):

even_lst = [i for i in lst if not i % 2]
odd_lst = [i for i in lst if i % 2]
Nin17
  • 2,821
  • 2
  • 4
  • 14
  • I tried this: def separate(list): even_list = [i for i in list if i % 2 == 0] uneven_list = [i for i in list if i % 2 != 0] But it has the same problems it returns the same list I used as the argument. If the list ends with an even number, it returns it as even_list, and the other way around if it ends with an uneven. I had to look up a little about list comprehensions, but it pretty much is a way to write a for with an if statement in one single line right? I also tried the original way you wrote the conditional, with the "not" and without the zero – Shize Apr 28 '22 at 00:58
  • @Shize can you show me what you're using as the variable ```list``` (which you should definitely rename) because this works for me – Nin17 Apr 28 '22 at 05:43