While loops - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: While loops (/thread-2298.html) |
While loops - Miraclefruit - Mar-06-2017 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? RE: While loops - micseydel - Mar-06-2017 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. RE: While loops - Larz60+ - Mar-06-2017 L = [2, 4, 6, 8] print(sum(L)) L = [] RE: While loops - sparkz_alot - Mar-06-2017 (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. RE: While loops - Miraclefruit - Mar-06-2017 Thank you, that's a way better to put it. RE: While loops - Larz60+ - Mar-06-2017 Why are you setting 'L' to an empty list? He empties the list in original post, just creating that condition RE: While loops - sparkz_alot - Mar-06-2017 Yeah, finally caught that after posting (see my edit) RE: While loops - nilamo - Mar-06-2017 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)) |