[Tutor] problem solving with lists: final (amateur) solution

Peter Otten __peter__ at web.de
Tue Jun 28 04:22:10 EDT 2022


On 27/06/2022 12:03, marcus.luetolf at bluewin.ch wrote:

> Just one replay to Peter's last issue:
> I used a copy of the original all_players list because I wanted to keep the
> original list unaltered.

[untested code below]

Technically you can alter a function

def chunks(items, chunksize):
     result = []
     while items:  # look, ma, no for-loop ;)
         result.append(items[:chunksize])
         del items[:chunksize]
     return result

into one that avoids the side effect of removing the entries from the 
items argument by making a copy:

def chunked(items, chunksize):
     return chunks(list(items))

But I doubt that any experienced programmer would write such code. You 
are far more likely to see

def chunked(items, chunksize):
     return [
         items[start: start + chunksize]
         for start in range(0, len(items), chunksize)
     ]

While you may find that a little more complex at first a general 
strategy that avoids "make a copy, then alter it" in favor of "build a 
new object from the current one(s)" makes for cleaner, more readable code.

The two things that made your script hard to understand for me were

(1) name mangling
(2) multiple just-in-case copies

It was not just me, though. The name mangling is what makes it hard to 
impossible for you to allow arbitrary player names.

The copies increase the number of variable names and the perceived 
complexity of your code. I can tell that you lost track of what was 
what, too, as there are places where you have lists that remain 
identical over the course of your script, and sometimes mistake a string 
for a list and write

players.extend(player)  # /seems/ to work for single-character
                         # player names

Finally: an excellent means to avoid design choices that make your code 
hard to maintain is to write tests early on in the design process. If 
it's hard to test it's a bad idea.

That's why I suggested doctest in my previous post.



More information about the Tutor mailing list