473,779 Members | 1,913 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

difference between `x in list` and `list.index(x)` for instances of anew-style class


Hello,

I have some code that stops when trying to find a graph in a list of
similar graphs::

(Pydb) list
110 try:
111 canonical = self.base[self.base.index (graph)]
112 except ValueError:
113 raise ValueError, \
114 "Cannot find canonical representative for graph `%s`." \
115 - % (repr(graph),)
116
....

The list `self.base` contains "canonical" forms of the graphs and the
`graph` object must compare equal to some item of the list, which
indeed it does::

(Pydb) p graph == self.base[27]
True

(Pydb) p graph in self.base
True

However, I cannot directly get the index of the canonical graph (the
number "27" above was found by manual inspection)::

(Pydb) self.base.index (graph)
*** ValueError: list.index(x): x not in list

All graphs are instances of a `Graph` new-style class that implements
comparison operators `__eq__` and `__ne__`, but no other rich-compare
stuff.

I'm using Python 2.5::

Python 2.5 (release25-maint, Dec 9 2006, 16:17:58)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2

So my question is: what are the implementation differences between `x
in list` and `list.index(x)` and why can one report that an item is in
the list while the other cannot find its index? Should I add
something to the `Graph` class so that `index` works?

Thanks for any hint!
--
Riccardo Murri, via Galeazzo Alessi 61, 00176 Roma

Dec 29 '07 #1
3 2421
On 28 dic, 20:12, Riccardo Murri <riccardo.mu... @gmail.comwrote :
The list `self.base` contains "canonical" forms of the graphs and the
`graph` object must compare equal to some item of the list, which
indeed it does::

* (Pydb) p graph == self.base[27] *
* True

* (Pydb) p graph in self.base
* True

However, I cannot directly get the index of the canonical graph (the
number "27" above was found by manual inspection)::

* (Pydb) self.base.index (graph)
* *** ValueError: list.index(x): x not in list

All graphs are instances of a `Graph` new-style class that implements
comparison operators `__eq__` and `__ne__`, but no other rich-compare
stuff.

I'm using Python 2.5::

* Python 2.5 (release25-maint, Dec *9 2006, 16:17:58)
* [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2

So my question is: what are the implementation differences between `x
in list` and `list.index(x)` and why can one report that an item is in
the list while the other cannot find its index? *Should I add
something to the `Graph` class so that `index` works?
(I've checked on 2.5.1 but I don't see any relevant differences with
the 2.5 version). Looking at the source for both methods, they only
use the __eq__ operator, but there is a slight difference: while one
evaluates list[i]==x, the other reverses the operands. If your __eq__
is not reflexive, that could explain the difference.

class Graph(object):
def __init__(self, *items):
self.items = items

def __eq__(self, other):
if len(self.items) >len(other.item s): return False
return self.items == other.items[:len(self.items )]

pyList = [Graph(1,2,3), Graph(4,5,6), Graph(1,2,3,4)]
pyg = Graph(1,2)
pyg in List
True
pyList.index(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list
pyList[0]==g
False
pyg==List[0]
True

In your example, see if self.base[27]==graph is still True.

--
Gabriel Genellina
Dec 29 '07 #2
bp*******@gmail .com writes:
On 28 dic, 20:12, Riccardo Murri <riccardo.mu... @gmail.comwrote :
>The list `self.base` contains "canonical" forms of the graphs and the
`graph` object must compare equal to some item of the list, which
indeed it does::

Â* (Pydb) p graph == self.base[27] Â*
Â* True

Â* (Pydb) p graph in self.base
Â* True

However, I cannot directly get the index of the canonical graph (the
number "27" above was found by manual inspection)::

Â* (Pydb) self.base.index (graph)
Â* *** ValueError: list.index(x): x not in list

All graphs are instances of a `Graph` new-style class that implements
comparison operators `__eq__` and `__ne__`, but no other rich-compare
stuff.

I'm using Python 2.5::

Â* Python 2.5 (release25-maint, Dec Â*9 2006, 16:17:58)
Â* [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2

So my question is: what are the implementation differences between `x
in list` and `list.index(x)` and why can one report that an item is in
the list while the other cannot find its index? Â*Should I add
something to the `Graph` class so that `index` works?

(I've checked on 2.5.1 but I don't see any relevant differences with
the 2.5 version). Looking at the source for both methods, they only
use the __eq__ operator, but there is a slight difference: while one
evaluates list[i]==x, the other reverses the operands. If your __eq__
is not reflexive, that could explain the difference.
That was indeed the reason: a bug in Graph.__eq__ broke reflexivity in
certain cases.

Thank you very much!!

--
Riccardo Murri, via Galeazzo Alessi 61, 00176 Roma

Dec 30 '07 #3
On 30 dic, 06:24, Riccardo Murri <riccardo.mu... @gmail.comwrote :
bpgbai...@gmail .com writes:
* (Pydb) p graph == self.base[27] *
* True
* (Pydb) p graph in self.base
* True
* (Pydb) self.base.index (graph)
* *** ValueError: list.index(x): x not in list
Looking at the source for both methods, they only
use the __eq__ operator, but there is a slight difference: while one
evaluates list[i]==x, the other reverses the operands. If your __eq__
is not reflexive, that could explain the difference.

That was indeed the reason: a bug in Graph.__eq__ broke reflexivity in
certain cases.
Combined with some other WTF bugs I've found at work, lately I feel
more like a detective than a software developer :)

--
Gabriel Genellina
Dec 30 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

33
3916
by: Jim Cobban | last post by:
I cannot get Netscape 4.79 to properly display the ordered list in the following fragment. <P>Get a specific portion of the date. Depending upon the value of index: <ol start=0> <li>complete value, usually as a <code>String</code>, or if an integral value as an <code>Integer</code>. <li>year as an <code>Integer</code> <li>month number as an <code>Integer</code>
12
1370
by: Aaron Prohaska | last post by:
I have been trying to figure out how to make the property values of two instances of the same control synchronize during a postback and need some help. I have posted an example of what I'm trying to do at this address http://64.84.11.209/. I would really appreciate any help with this. I'm actually surprised that no one else seems to be doing this or having the same problem. The functionality I'm trying to make work I think would be very...
4
2491
by: techiepundit | last post by:
I'm a Python newbie who just started learning the language a few weeks ago. So these are beginner questions. I have a list of sockets that I use for select.select calls like this: ReadList,WriteList,EventList = select.select(self.SocketList,,,3) In parallel with that list of sockets I want something that is like a list of socket,PacketFragment pairs. I need this because I could do recv and get part of a sent packet. I want to loop...
3
2102
by: Varangian | last post by:
Hello, there I have a problem with regards to System.Collections.Generic.List<T> I need to pass a class with implements an interface - TestClass : IPerson I put this class in a List<TestClass> = new List<TestClass>(); then I pass this List<TestClass> to a function which takes an argument List<IPerson> person
18
1295
by: Daniel | last post by:
My previous thread got very large so here is my point again, but a better example of my problem: SceneChair chair = (SceneChair)_objMan.GetObject((int)ObjectID.Seats); chair.Position = GetSeatPosition(1); chair.FrameNum = 1; _objMan.AddToRenderStack(chair);
0
2593
by: mel_apiso | last post by:
Hi, after uncatalog one database, and catalog again with other name, if I try to connect with this database, everything is ok, but list applications only show me the connection with the uncatalog/catalog database. After I disconnect from this database, list applications command show all instances connection. Below I paste the situation.
35
29232
by: erikwickstrom | last post by:
Hi all, I'm sorry about the newbie question, but I've been searching all afternoon and can't find the answer! I'm trying to get this bit of code to work without triggering the IndexError. import shutil, os, sys
6
1823
by: Savante | last post by:
I have been writing a datalogging application. It reads in double's into a database. I want to be able to click on a row in a database (holds name of variable and also current value of variable) and then instantiate a new form. I created a new form form2 and then just on double click on a button.... dim form as new form2 form.show
2
2459
theaybaras
by: theaybaras | last post by:
Hi all, I have a table and a subtable . CAssessments is a combobox that looks up a table called AssessList has 2 columns, an autonumber PK and a string for the title of the Assessment. When the user meets with a client, they input the valid demographic details and time spent with client, and then in the subtable CAssessments they input any assessments they ran with their client. I need to have a report of the total number of hours...
14
2188
by: puzzlecracker | last post by:
I noticed in my code, which is essentially an api for the client, that I return ArrayList object to the client. In my case, list consist of some objects that user only need to iterate over, hence no modification to list is done after it filled by me. What do you think is the best data structure for this requirement? Thanks
0
10306
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10138
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9930
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8961
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6724
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5373
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5503
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2869
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.