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
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
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.
random.sample(...)"sum(1 for value in random.sample(range(1000), 250) if value % 2).