Mar-06-2017, 12:05 AM
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?
While loops
|
Mar-06-2017, 12:05 AM
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?
Mar-06-2017, 12:16 AM
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.
Mar-06-2017, 12:30 AM
L = [2, 4, 6, 8] print(sum(L)) L = []
Mar-06-2017, 01:03 AM
(This post was last modified: Mar-06-2017, 01:03 AM by sparkz_alot.)
(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
Mar-06-2017, 01:49 AM
Thank you, that's a way better to put it.
Mar-06-2017, 03:36 AM
Why are you setting 'L' to an empty list?
He empties the list in original post, just creating that condition
Mar-06-2017, 02:00 PM
Yeah, finally caught that after posting (see my edit)
![]()
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
Mar-06-2017, 09:30 PM
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)) |
|