[Tutor] Test Question

John Steedman johnsteedman360 at gmail.com
Mon Jul 1 21:27:12 CEST 2013


Many thanks, everyone.  Great answers. I decided to read the manual
properly.  May take some time but well worth it.


On Mon, Jul 1, 2013 at 2:40 PM, Steven D'Aprano <steve at pearwood.info> wrote:

> On 01/07/13 19:58, John Steedman wrote:
>
>> Good morning all,
>>
>> A question that I am unsure about.  I THINK I have the basics, but I am
>> not
>> sure and remain curious.
>>
>> 1. What does this mean?
>>
>>> if my_object in my_sequence:
>>>>>
>>>> ...
>>
>
>
> Others have already answered this, but for completion, it is testing
> whether "my_object" can be found as an element of the sequence, iterable,
> or container "my_sequence".
>
>
>
>  2. What can go wrong with this? What should a code review pick up on?
>>
>
> Depends on context. Without context, nearly anything could go wrong:
>
> NameError -- perhaps one or both of the names are undefined;
>
> TypeError -- perhaps the names are misleading, and my_sequence is not a
> sequence at all;
>
> Perhaps my_sequence is an infinite iterator and the above will never
> complete;
>
> etc.
>
>
>  I believe that "my_sequence" might be a either container class or a
>> sequence type. An effective __hash__ function would be required for each
>> "my_object".
>>
>
> Correct, if my_sequence is in fact a dict or other mapping that relies on
> hashing.
>
> But in fact it's not just the presence of a __hash__ method on my_object
> which is required, but that the __hash__ method can actually return. E.g.
> tuples have a __hash__ method, but that relies on every element of the
> tuple being hashable:
>
> py> (1, 2, 3) in {}
> False
> py> (1, 2, [3]) in {}
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: unhashable type: 'list'
>
>
>
>  I HTINK you'd need to avoid using floating point variables
>> that might round incorrectly.
>>
>
> No, Python floats are not rounded when doing containment testing. They may
> have been rounded earlier, but `x in container` will use the full precision
> of the float.
>
>
>  Are there other issues?
>>
>
> Nothing obvious to me.
>
>
>
>
>
> --
> Steven
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130701/03e73141/attachment.html>


More information about the Tutor mailing list