Python Forum
penjee . com and non-pythonic code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
penjee . com and non-pythonic code
#4
for me 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)
Reply


Messages In This Thread
penjee . com and non-pythonic code - by buran - Feb-21-2017, 02:27 PM
RE: penjee . com and non-pythonic code - by nilamo - Feb-28-2017, 08:15 PM
RE: penjee . com and non-pythonic code - by buran - Feb-28-2017, 09:09 PM
RE: penjee . com and non-pythonic code - by wavic - Feb-28-2017, 09:18 PM
RE: penjee . com and non-pythonic code - by buran - Feb-28-2017, 09:34 PM
RE: penjee . com and non-pythonic code - by wavic - Feb-28-2017, 09:38 PM
RE: penjee . com and non-pythonic code - by buran - Feb-28-2017, 09:46 PM
RE: penjee . com and non-pythonic code - by nilamo - Feb-28-2017, 09:41 PM
RE: penjee . com and non-pythonic code - by Ofnuts - Feb-28-2017, 09:54 PM
RE: penjee . com and non-pythonic code - by wavic - Feb-28-2017, 10:30 PM
RE: penjee . com and non-pythonic code - by zivoni - Feb-28-2017, 10:57 PM
RE: penjee . com and non-pythonic code - by nilamo - Feb-28-2017, 11:03 PM
RE: penjee . com and non-pythonic code - by Ofnuts - Mar-01-2017, 08:12 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  system programming in pythonic code Skaperen 3 3,002 Jun-21-2018, 01:57 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020