# Efficient Checking Method? browsing

• posted
0

Is there anyone who thinks this is a bad idea for checking for odd numbers, and adding them to a list for later use?

``````nums_list = []
for number in range(1000): # This makes a list with a ton of uneven numbers.
eoro_check = (number-1)%2
if eoro_check == 0:
pass
else:
if number-1 == -1:
pass
else:
nums_list.append(number-1)
print nums_list
``````

• posted
0

``````nums_list=[n for n in range(1000) if n%2]
``````

In plain English, `nums_list` is each item in `range(1000)` IF that item is not evenly divisible by 2.
This works because if `n` is even, then `n%2` is `0` (evenly divisible by 2) and therefore `False`. If `n` is odd, `n%2` is 1, and therefore true.

• posted
0

@Webmaster4o

Yeah, I understand what it does. But is there another built-in/more efficient way of doing it?

• posted
0

@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.

• posted
0

@Webmaster4o alright, thanks!

• posted
2

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
``````

• posted
0

@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 `range()` a ton.

• posted
0

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 `range()`.

http://stackoverflow.com/questions/15014310/why-is-there-no-xrange-function-in-python3

• posted
0

@ccc that's interesting. Too bad I wouldn't know as omz refuses to work on getting Python 3 in.

• posted
1

That is why God invented other computers.

Got \$5?

• posted
0

@ccc lol, I am getting one.

• posted
2

@AtomBombed

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.

Internal error.

Oops! Looks like something went wrong!