[Tutor] List vs. Set:

Steven D'Aprano steve at pearwood.info
Sun Feb 25 04:44:16 EST 2018


On Sat, Feb 24, 2018 at 08:00:58PM +0000, James Lundy wrote:

> Could this be a bug in my Pycharm 3 compiler I have had mixed 
> experiences running the code.

As a general rule, any time you get an unexpected error and think "Could 
this be a bug in the compiler?", the chances are almost always "No".

Which is more likely?

- tens or hundreds of thousands of people have used this compiler, and 
never noticed this bug? or

- the bug is in my code?

Even for experts, the chances are that the bug is in their code. The 
difference between the expert and the beginner is that the expert has a 
good shot at recognising that one-in-a-million time that it actually is 
an undiscovered bug in the compiler.

In the case of your code, I think the problem is this line:

>         gooddata.append({singleday[2], singleday[3], singleday[4], singleday[5]})

In particular, the part between the curly brackets (braces):

    # curly brackets make a set
    { singleday[2], ... }

makes a set. My guess is that you were intending a list:

    # square brackets make a list
    [ singleday[2], ... ]

But there's a better way to fix this. You are grabbing four items out of 
a list, in order. Python has a short-cut for doing that:

    # the long way
    [singleday[2], singleday[3], singleday[4], singleday[5]]

    # the short (and faster!) way
    singleday[2:6]

Notice that the first index (2) is included, but the second index (6) is 
excluded. While it might seem confusing at first, this actually helps 
prevent "off by one" errors.

So the troublesome line becomes:

    gooddata.append(singleday[2:6])

and, I believe, that ought to fix the bug. Possibly, or possibly not, 
to reveal any more bugs... *smiles*


Regards,


-- 
Steve


More information about the Tutor mailing list