Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loops
#8
If you really wanted to use a while loop, you could just check against the list itself (an empty list is the same as False), and .pop() instead of re-building the list each iteration.  So...
items = [2, 4, 6, 8]
total = 0
while items:
   total += items.pop()
print(total)
Or, if you're a map/reduce/functional fan (and don't want to just use sum() for some reason), then there's yet another way:
from functools import reduce
import operator

items = [2, 4, 6, 8]
print(reduce(operator.add, items))
Reply


Messages In This Thread
While loops - by Miraclefruit - Mar-06-2017, 12:05 AM
RE: While loops - by micseydel - Mar-06-2017, 12:16 AM
RE: While loops - by Larz60+ - Mar-06-2017, 12:30 AM
RE: While loops - by sparkz_alot - Mar-06-2017, 01:03 AM
RE: While loops - by Miraclefruit - Mar-06-2017, 01:49 AM
RE: While loops - by Larz60+ - Mar-06-2017, 03:36 AM
RE: While loops - by sparkz_alot - Mar-06-2017, 02:00 PM
RE: While loops - by nilamo - Mar-06-2017, 09:30 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020