1

I'm relatively new to Python and have been told to create a list using list comprehension to only display even numbers between 0-100 then add all of those numbers together. I understand how to do it if it was just a regular list such as:

Total = 0
for x in range (0,101,2):
     Total += x

I have no idea what to do though with the comprehension. It makes no sense to me. This is what I have.

Total = 0 
x = [x for x in range (1001) if x % 2 ==0]


Total +=int(???)
print('The total is:', Total)

I don't know what to put in for the ??? or even if I'm going about this the right way. Any help would be great!

Edit: I forgot to mention it needs to be in a for loop. I don't know how to create the for loop and the comprehension list.

John
  • 13
  • 3

5 Answers5

2

sum

Looking at this answer :

sum([x for x in range(101) if x%2 == 0])
#=> 2550

for and comprehension

total = 0
for even in [i for i in range(101) if i%2 == 0]:
     total += even
total
#=> 2550

Direct formula

n = 100
(n/2)*(n/2+1)
#=> 2550
Community
  • 1
  • 1
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
1

To do it with list comprehensions:

print(sum([x for x in range(0,101,2)]))

But you can just do:

print(sum(range(0,101,2)))

The output in both cases is 2550.


So apparently your requirements are to use a list comprehension and a for loop? I'm a bit confused but are you asking for this?

even_terms = [x for x in range(0,101,2)]

total = 0
for x in even_terms:
    print(x)
    total += x

print('total:', total)

Output

0
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100
total: 2550
Tagc
  • 8,736
  • 7
  • 61
  • 114
0
Total = reduce( lambda x, y: x + y, filter( lambda n: n % 2 == 0, range( 0, 101 )  )

or

Total = reduce( lambda x, y: x + y, range( 0, 101, 2 ) )
Reaper
  • 747
  • 1
  • 5
  • 15
0

Your first example was correct. Both range and the list produced by the comprehension are iterable, so they both work in a for-loop. Just replace the range with the comprehension:

xs = [x for x in range (1001) if x % 2 ==0]

Total = 0
for x in xs:
     Total += x

print(Total) 
Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
0

Using sum is probably the canonical method for iterating over a list comprehension when adding.

def calculate_sum_over_range(start, end, interval=2):
    return sum(_ for _ in range(start, end, interval))

print(calculate_sum_over_range(0, 101))

Good luck on your homework assignment.

Brian Bruggeman
  • 5,008
  • 2
  • 36
  • 55