473,652 Members | 2,979 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

checking if an object IS in a list

Hi,

I want to test if an object IS in a list (identity and not equality
test).
I can if course write something like this :

test = False
myobject = MyCustomClass(* args, **kw)
for element in mylist:
if element is myobject:
test = True
break

and I can even write a isinlist(elt, mylist) function.

But most of the time, when I need some basic feature in python, I
discover later it is in fact already implemented. ;-)

So, is there already something like that in python ?
I tried to write :
'element is in mylist'
but this appeared to be incorrect syntax...

All objects involved all have an '__eq__' method.
Thanks,

N. P.

PS: Btw, how is set element comparison implemented ? My first
impression was that 'a' and 'b' members are considered equal if and
only if hash(a) == hash(b), but I was obviously wrong :
>>class A(object):
.... def __eq__(self,y):
.... return False
.... def __hash__(self):
.... return 5
....
>>a=A();b=A()
a==b
False
>>hash(b)==hash (a)
True
>>b in set([a])
False
>>S=set([a])
S.differenc e([b])
set([<__main__.A object at 0xb7a91dac>])

So there is some equality check also, maybe only if '__eq__' is
implemented ?
Jul 18 '08 #1
20 3100
ni************* **@gmail.com wrote:
Hi,

I want to test if an object IS in a list (identity and not equality
test).
I can if course write something like this :

test = False
myobject = MyCustomClass(* args, **kw)
for element in mylist:
if element is myobject:
test = True
break

and I can even write a isinlist(elt, mylist) function.

But most of the time, when I need some basic feature in python, I
discover later it is in fact already implemented. ;-)

So, is there already something like that in python ?
I tried to write :
'element is in mylist'
but this appeared to be incorrect syntax...
There is no "is in" operator in Python, but you can write your test more
concisely as

any(myobject is element for element in mylist)

PS: Btw, how is set element comparison implemented ? My first
impression was that 'a' and 'b' members are considered equal if and
only if hash(a) == hash(b), but I was obviously wrong :
>>>class A(object):
... def __eq__(self,y):
... return False
... def __hash__(self):
... return 5
...
>>>a=A();b=A( )
a==b
False
>>>hash(b)==has h(a)
True
>>>b in set([a])
False
>>>S=set([a])
S.difference ([b])
set([<__main__.A object at 0xb7a91dac>])

So there is some equality check also, maybe only if '__eq__' is
implemented ?
In general equality is determined by __eq__() or __cmp__(). By default
object equality checks for identity.

Some containers (like the built-in set and dict) assume that a==b implies
hash(a) == hash(b).

Peter
Jul 18 '08 #2
On 18 juil, 11:30, Peter Otten <__pete...@web. dewrote:
nicolas.pource. ..@gmail.com wrote:
Hi,
I want to test if an object IS in a list (identity and not equality
test).
I can if course write something like this :
test = False
myobject = MyCustomClass(* args, **kw)
for element in mylist:
* * if element is myobject:
* * * * test = True
* * * * break
and I can even write a isinlist(elt, mylist) function.
But most of the time, when I need some basic feature in python, I
discover later it is in fact already implemented. ;-)
So, is there already something like that in python ?
I tried to write :
'element is in mylist'
but this appeared to be incorrect syntax...

There is no "is in" operator in Python, but you can write your test more
concisely as

any(myobject is element for element in mylist)
Thanks a lot
However, any() is only available if python version is >= 2.5, but I
may define a any() function on initialisation, if python version < 2.5

I think something like
>>id(myobject ) in (id(element) for element in mylist)
would also work, also it's not so readable, and maybe not so fast
(?)...

An "is in" operator would be nice...
PS: Btw, how is set element comparison implemented ? My first
impression was that 'a' and 'b' members are considered equal if and
only if hash(a) == hash(b), but I was obviously wrong :
>>class A(object):
... def __eq__(self,y):
... return False
... def __hash__(self):
... return 5
...
>>a=A();b=A()
a==b
False
>>hash(b)==hash (a)
True
>>b in set([a])
False
>>S=set([a])
S.differenc e([b])
set([<__main__.A object at 0xb7a91dac>])
So there is some equality check also, maybe only if '__eq__' is
implemented ?

In general equality is determined by __eq__() or __cmp__(). By default
object equality checks for identity.

Some containers (like the built-in set and dict) assume that a==b implies
hash(a) == hash(b).

Peter
So, precisely, you mean that if hash(a) != hash(b), a and b are
considered distinct, and else [ie. if hash(a) == hash(b)], a and b are
the same if and only if a == b ?
Jul 18 '08 #3
In fact, 'any(myobject is element for element in mylist)' is 2 times
slower than using a for loop, and 'id(myobject) in (id(element) for
element in mylist)' is 2.4 times slower.

Jul 18 '08 #4
ni************* **@gmail.com wrote:
I think something like
>>>id(myobjec t) in (id(element) for element in mylist)
would also work, also it's not so readable, and maybe not so fast
(?)...

An "is in" operator would be nice...
And rarely used. Probably even less than the (also missing)

< in, | in, you-name-it

operators...
So, precisely, you mean that if hash(a) != hash(b), a and b are
considered distinct, and else [ie. if hash(a) == hash(b)], a and b are
the same if and only if a == b ?
Correct for set, dict. For lists etc. the hash doesn't matter:
>>class A(object):
.... def __hash__(self):
.... return nexthash()
.... def __eq__(self, other):
.... return True
....
>>from itertools import count
nexthash = count().next
A() in [A() for _ in range(3)]
True
>>d = dict.fromkeys([A() for a in range(3)])
d.keys()[0] in d
False

Peter
Jul 18 '08 #5
ni************* **@gmail.com wrote:
In fact, 'any(myobject is element for element in mylist)' is 2 times
slower than using a for loop, and 'id(myobject) in (id(element) for
element in mylist)' is 2.4 times slower.
This is not a meaningful statement unless you at least qualify with the
number of item that are actually checked. For sufficently long sequences
both any() and the for loop take roughly the same amount of time over here.

$ python -m timeit -s"items=range(1 000); x = 1000" "any(x is item for item
in items)"
1000 loops, best of 3: 249 usec per loop
$ python -m timeit -s"items=range(1 000); x = 1000" "for item in items:" "
if x is item: break"
1000 loops, best of 3: 276 usec per loop

$ python -m timeit -s"items=range(1 000); x = 0" "any(x is item for item in
items)"
100000 loops, best of 3: 3 usec per loop
$ python -m timeit -s"items=range(1 000); x = 0" "for item in items:" " if x
is item: break"
1000000 loops, best of 3: 0.317 usec per loop
Peter

PS: Take these numbers with a grain of salt, they vary a lot between runs.
Jul 18 '08 #6
On 18 juil, 12:26, Peter Otten <__pete...@web. dewrote:
nicolas.pource. ..@gmail.com wrote:
I think something like
>>id(myobject ) in (id(element) for element in mylist)
would also work, also it's not so readable, and maybe not so fast
(?)...
An "is in" operator would be nice...

And rarely used. Probably even less than the (also missing)

< in, | in, you-name-it

operators...
Maybe, but imho
>>myobject is in mylist
is highly readable, when
>>myobject < in mylist
is not.
Jul 18 '08 #7
On 18 juil, 13:13, Peter Otten <__pete...@web. dewrote:
nicolas.pource. ..@gmail.com wrote:
In fact, 'any(myobject is element for element in mylist)' is 2 times
slower than using a for loop, and 'id(myobject) in (id(element) for
element in mylist)' is 2.4 times slower.

This is not a meaningful statement unless you at least qualify with the
number of item that are actually checked. For sufficently long sequences
both any() and the for loop take roughly the same amount of time over here.
Sorry. I used short lists (a list of 20 floats) and the element
checked was not in the list.
(That was the case I usually deals with in my code.)
Jul 18 '08 #8
ni************* **@gmail.com wrote:
On 18 juil, 13:13, Peter Otten <__pete...@web. dewrote:
>nicolas.pource ...@gmail.com wrote:
In fact, 'any(myobject is element for element in mylist)' is 2 times
slower than using a for loop, and 'id(myobject) in (id(element) for
element in mylist)' is 2.4 times slower.

This is not a meaningful statement unless you at least qualify with the
number of item that are actually checked. For sufficently long sequences
both any() and the for loop take roughly the same amount of time over
here.

Sorry. I used short lists (a list of 20 floats) and the element
checked was not in the list.
(That was the case I usually deals with in my code.)
What is your (concrete) use case, by the way?

If you want efficiency you should use a dictionary instead of the list
anyway:

$ python -m timeit -s"d=dict((id(i) , i) for i in range(1000)); x =
1000" "id(x) in d"
1000000 loops, best of 3: 0.275 usec per loop

Peter
Jul 18 '08 #9
Peter Otten:
PS: Take these numbers with a grain of salt, they vary a lot between runs.
Another possibility :-)
from itertools import imap
id(x) in imap(id, items)

>If you want efficiency you should use a dictionary instead of the list anyway:
I agree, but sometimes you have few items to look for, so building the
whole dict (that requires memory too) may be a waste of time.

In theory this may be faster to build, but in practice you need a
benchmark:
ids = set(imap(id, items))
followed by:
id(x) in ids

Bye,
bearophile
Jul 18 '08 #10

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

Similar topics

7
7575
by: - ions | last post by:
I have created a JComboBox with its Items as a list of "M" numbers ie. M1,M2,M3.......throgh too M110 (thes are the messier objects, a catolouge of deep sky objects) the user selects of of these and views it aswell as infomation. The program also has a JTextFiels which allows the user to enter the M number. The problem i have is checking that what the user has entered is valid, that being an M followed by 1 - 110 Nothing else, i thought of...
3
2348
by: George Sakkis | last post by:
Explicit type checking is not typically seen in Python code, and usually that's not a big problem; most typing errors are likely to raise a TypeError or AttributeError sooner than later. There are cases, though, where typing errors are not caught (at least not early) because different classes happen to have methods with the same name; that's really subtle with the special methods like __eq__, __hash__, etc. that are common to all (or at...
5
2995
by: Tongu? Yumruk | last post by:
I have a little proposal about type checking in python. I'll be glad if you read and comment on it. Sorry for my bad english (I'm not a native English speaker) A Little Stricter Typing in Python - A Proposal As we all know, one of the best things about python and other scripting languages is dynamic typing (yes I know it has advantages and disadvantages but I will not discuss them now). Dynamic typing allows us to change types of...
0
1084
by: Paddy | last post by:
Hi, I read a blog entry by GVR on interfaces in which he mentioned that you had to be able to state the type signature of, say, a function. That got me thinking along the lines of: If you have some typical data, then transform it into a string showing its sub-types. Could not a regular expression matching this string be used to check the type signature of the data?
0
1473
by: Mike Meyer | last post by:
The recent thread on threads caused me to reread the formal definition of SCOOP, and I noticed something I hadn't really impressed me the first time around: it's using staticly checkable rules to help ensure correct behavior in a concurrent environment. That's impressive. That's *really* impressive. I know of no other language that does that - though they probably exist. I'd be interested in references to them. Normally, I think of...
8
3253
by: Jack Addington | last post by:
I want to scroll through the alphabet in order to scroll some data to the closest name that starts with a letter. If the user hits the H button then it should scroll to the letter closest to H. If no one exists with H, then go to I, etc. If its near the end, say 'V', and the last person is a 'T' then it should work its way back up the alphabet. I was trying to loop as if the Char's were ints but I am having problems I have buttons...
1
1428
by: Tom Leylan | last post by:
I'm either passing the wrong thing, comparing the wrong thing or... something else. I have a CSharp base class which is used to fire events and in CSharp I have defined a delegate for the custom eventhandler. I use this as a subclass for classes created in VB.Net. I realize I can define it all in VB.Net but I need it done this way. I can add an eventhandler in a VB.Net app to the VB.Net object I've created and all the events are...
4
6050
by: Darrel | last post by:
I'm trying to add an extra layer of error checking on a Drop Down List. The list is populated from one table, and then I select the selectedValue from another DB. While it SHOULDN'T ever happen, just incase, I want to check that the selected value actually exists as a value in the dropDownList before I actually try to select it. I've tried this:
8
1877
by: Brendan | last post by:
There must be an easy way to do this: For classes that contain very simple data tables, I like to do something like this: class Things(Object): def __init__(self, x, y, z): #assert that x, y, and z have the same length But I can't figure out a _simple_ way to check the arguments have the
16
3449
by: Joe Strout | last post by:
Let me preface this by saying that I think I "get" the concept of duck- typing. However, I still want to sprinkle my code with assertions that, for example, my parameters are what they're supposed to be -- too often I mistakenly pass in something I didn't intend, and when that happens, I want the code to fail as early as possible, so I have the shortest possible path to track down the real bug. Also, a sufficiently clever IDE could use...
0
8279
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8467
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8589
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
7302
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...
1
6160
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5619
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();...
1
2703
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
1
1914
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1591
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.