Python Forum

Full Version: While loops
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
L = [2, 4, 6, 8]
total = 0
while L != []:
     total += L[0]
     L = L[1:]
print(total)
How do I make this snippet simplified/clearer?
Could you give us more context? This computes the sum of a list (inefficiently). So print(sum(L)) would do it, unless you have other restrictions.
L = [2, 4, 6, 8]
print(sum(L))
L = []
(Mar-06-2017, 12:30 AM)Larz60+ Wrote: [ -> ]
L = [2, 4, 6, 8]
print(sum(L))
L = []

Why are you setting 'L' to an empty list?

Edit:
Never mind, I see that is what the OP ends up with, though I'm not sure why he would want that.
Thank you, that's a way better to put it.
Why are you setting 'L' to an empty list?
He empties the list in original post, just creating that condition
Yeah, finally caught that after posting (see my edit)   Smile
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))