On 2017-02-23 23:00, Deborah Swanson wrote:


-----Original Message-----
From: Erik [mailto:pyt...@lucidity.plus.com]
Sent: Thursday, February 23, 2017 2:09 AM
To: pyt...@deborahswanson.net; python-list@python.org
Subject: Re: Namedtuples problem


Hi,

On 23/02/17 09:38, Deborah Swanson wrote:
> group[[idx][records_idx[label]]]
> gets an IndexError: list index out of range

[snip]

> Can anyone see why I'm getting this Index error? and how to fix it?

It looks to me like you are indexing into a single-element
list that you
are creating using the literal list syntax in the middle of
the expression.

Actually, group is essentially a 2-element list. Each group has a list
of rows, and each row has a set of fields. group has to be indexed by
row index and field index. (This is a namedtuple configuration.)

The weirdness is that

group[0][4]

gets the right answer, but

group[[idx][records_idx[label]]],
where idx = 0 and records_idx[label]] = 4

gets the IndexError.

It's not weird. As Erik says below, and I'll repeat here, you have:

    group[[idx][records_idx[label]]]

That consists of the expression:

    [idx][records_idx[label]]

within:

    group[...]

The [idx] creates a one-element list.

You then try to subscript it with records_idx[label]. If records_idx[label] is anything other than 0 (or -1), it'll raise IndexError because there's only one element in that list.

If you substitute idx == 0 and records_idx[label]] == 4 into:

    group[[idx][records_idx[label]]]

you'll get:

    group[[0][4]]

which is not the same thing as group[0][4]!

If we were to break the expression into parts to make it a
bit simpler
to refer to discuss:

ridx = records_idx[label]
group[[idx][ridx]]

You can now more easily see that 'group' is being indexed by the
expression "[idx][ridx]". What does that mean?

[idx] is creating a single-element list using literal list
syntax. This
is then indexed using 'ridx' (using, perhaps confusingly, the
exact same
syntax to do a different thing).

The result of *that* expression is then being used to index
'group', but
it won't get that far because you'll get the exception if 'ridx' is
anything but zero.

So the initial problem at least is the extra [] around 'idx' which is
creating a list on the fly for you.


--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to