Op 28-03-16 om 03:05 schreef Steven D'Aprano:
> On Mon, 28 Mar 2016 05:01 am, Marco S. wrote:
>
>> Steven D'Aprano wrote:
>>
>>> The point you might have missed is that treating lists as if they were
>>> mappings violates at least one critical property of mappings: that the
>>> relationship between keys and values are stable.
>>
>> This is true for immutable maps, but for mutable ones, you can simply do
> No, it is true for mutable maps too.
>
> When you add a new key:value to a dict, the other key:value pairs don't
> change. That is the whole point of a mapping! Of course you can
> deliberately change the value by re-assignment:
>
>     map[key] = new_value
>
> but that's not what I'm talking about. When you add a NEW key, the OTHER
> keys DON'T change. That is ABSOLUTELY CRITICAL to a mapping. Anything which
> lacks that property is not a mapping.

I'm not sure I agree with that.

> The relationship between the index of a value and the value in a sequence is
> not stable. Inserting a new value can change the "key"(actually index) of
> some or all of the existing values.

Which is not simply adding a key. Inserting a new value is IMO more like
doing an update.

>  The whole point of sequences is that
> the position of values is NOT stable: they are intended to move around.

I find that language too strong. The lists I use are generally stable.
Does that mean I'm using lists in a way not intended.

>  You
> can sort them, reverse them, delete them, insert new values, and the others
> will move around to make room. If you think of the index as a key, this is
> completely the opposite behaviour of mappings.

Not really. IMO a mapping is just a surjective function and sometimes a
list is a perfectly fine way to implement such a function.

The point I think the OP tries to make is that sometimes you need to write
a function that takes a surjective function as argument and produces some
result, but you just don't care whether this function is implemented as
a map or as a sequence.

Suppose you want to know how many times each value occurs and want to
map that. As it is you have to write something like the following.

def count(l):
    counted = defaultdict(int)
    try:
        itr = l.values()
    except AttributeError:
        itr = iter(l)
    for v in itr:
        counted[v] += 1
    return counted

What would be the big problem if a values method would be available
on a list which returned the iterator and if an items method would
be like calling enumerate?

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

Reply via email to