0

How can I avoid having to increment the count_odd_values variable manually in the following Python code:

count_odd_values = 0
for value in random.sample(range(1000), 250):
  if value % 2 == 1:
    count_odd_values += 1
1
  • @Josh Thanks, but I don't see how. I am new to Python. Commented Aug 23, 2013 at 3:23

1 Answer 1

3

You can do:

count_odd_values = sum(value % 2 for value in random.sample(range(1000), 250))

All the even numbers will give value % 2 == 0 and will not change the sum. All the odd numbers will give value % 2 == 1 and sum will be incremented by 1.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, i assume this would generalize to a condition that checks a database object in django?
Sorry, can't say much for Django, not experienced. All I know is that this code will count odd numbers in "whatever's provided by random.sample(...)"
Less useless addition would be required with sum(1 for value in random.sample(range(1000), 250) if value % 2).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.