'How to separate numbers from an iterable in two lists of even and odd numbers?
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.
Solution 1:[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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nin17 |
