Efficient Checking Method?
nums_list=[n for n in range(1000) if n%2]
In plain English,
nums_listis each item in
range(1000)IF that item is not evenly divisible by 2.
This works because if
nis even, then
0(evenly divisible by 2) and therefore
n%2is 1, and therefore true.
Yeah, I understand what it does. But is there another built-in/more efficient way of doing it?
@AtomBombed Actually, I might have something else.
range(1,1000,2)is more efficient both time wise, and length wise, and it's pretty "built in". That's as "built-in" as you're gonna get.
However, if you're not looking for odd numbers and that's just an example, then a list comprehension is a pretty good method for general checking, the most compact and most efficient that I know of.
@Webmaster4o alright, thanks!
ccc last edited by ccc
In Python 2, you should almost always choose to use xrange() instead of range() for performance and memory management reasons...
import sys print(sys.getsizeof(range(1000))) # 8064 print(sys.getsizeof(xrange(1000))) # 20 print(sys.getsizeof(range(1000000))) # 4000032 that is 4MB of RAM instead of 20 bytes print(sys.getsizeof(xrange(1000000))) # 20
@ccc oh thanks! I had no idea the difference. I didn't even know there was an
xrange(). I will be sure to use that, as I use for loops with
ccc last edited by
The thing that will really warp your mind is that the
range()implementation is removed from Python3 and the
xrange()implementation is improved to deal with arbitrarily large numbers and renamed to
@ccc that's interesting. Too bad I wouldn't know as omz refuses to work on getting Python 3 in.
ccc last edited by
That is why God invented other computers.
@ccc lol, I am getting one.
omz refuses to work on getting Python 3 in.
I think that's a little harsh, he's just finished the fantastic 2.0 update, and he hasn't said he won't upgrade, it's just not his top priority.