necromancer
necromancer

Reputation: 24641

Avoid conditional counter increment in Python loop

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

Upvotes: 0

Views: 295

Answers (1)

mishik
mishik

Reputation: 10003

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.

Upvotes: 3

Related Questions