Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting every odd variable in a list?

Tags:

python

If I make a list in Python and want to write a function that would return only odd numbers from a range 1 to x how would I do that?

For example, if I have list [1, 2, 3, 4] from 1 to 4 (4 ix my x), I want to return [1, 3].

like image 210
John Avatar asked Dec 04 '22 14:12

John


1 Answers

If you want to start with an arbitrary list:

[item for item in yourlist if item % 2]

but if you're always starting with range, range(1, x, 2) is better!-)

For example:

$ python -mtimeit -s'x=99' 'filter(lambda(t): t % 2 == 1, range(1, x))'
10000 loops, best of 3: 38.5 usec per loop
$ python -mtimeit -s'x=99' 'range(1, x, 2)'
1000000 loops, best of 3: 1.38 usec per loop

so the right approach is about 28 times (!) faster than a somewhat-typical wrong one, in this case.

The "more general than you need if that's all you need" solution:

$ python -mtimeit -s'yourlist=range(1,99)' '[item for item in yourlist if item % 2]'
10000 loops, best of 3: 21.6 usec per loop

is only about twice as fast as the sample wrong one, but still over 15 times slower than the "just right" one!-)

like image 188
Alex Martelli Avatar answered Dec 06 '22 03:12

Alex Martelli