Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loops
#1
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?
Reply
#2
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.
Reply
#3
L = [2, 4, 6, 8]
print(sum(L))
L = []
Reply
#4
(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.
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#5
Thank you, that's a way better to put it.
Reply
#6
Why are you setting 'L' to an empty list?
He empties the list in original post, just creating that condition
Reply
#7
Yeah, finally caught that after posting (see my edit)   Smile
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply
#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


Forum Jump:

User Panel Messages

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