for me
also I don't like comparison to 0.
for number in numbers
loop is the best and most pythonic in this case. while numbers
is better than while len(numbers)>0
, but still you still need to use pop()
(inefficient compared to the for loop - it will make difference if long list, because you change and reindex the list with every iteration). if you HAVE TO, then use collections.deque
, especially for long lists.also I don't like comparison to 0.
key = 'odd' if num % 2 else 'even'By the way, I don't like ternary conditional operator and use it only in really trivial cases (e.g. in this case it is OK).
numbers = [12, 37, 5, 42, 8, 3] odd=[] even=[] for num in numbers: if num % 2: odd.append(num) else: even.append(num)following is also nice, but maybe not that explicit
from collections import defaultdict numbers = [12, 37, 5, 42, 8, 3] separated = defaultdict(list) for num in numbers: separated[num%2].append(num)