473,734 Members | 2,370 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

implementation of "in" that returns the object.

Hi

I need to check if an object is in a list AND keep a reference to the
object I have done it this way but is there a better one?
>>def inplusplus(valu e,listObj):
.... for i in listObj:
.... if i is value:
.... return value
.... return False
....
>>l = [1,2,3,4]
print inplusplus(2,l)
2
>>print inplusplus(9,l)
False
>>print inplusplus(1,l)
1
>>l.append(0)
print inplusplus(0,l)
0
Oct 22 '06 #1
6 953
In <ma************ *************** ***********@pyt hon.org>, Jorge Vargas
wrote:
I need to check if an object is in a list AND keep a reference to the
object I have done it this way but is there a better one?
But you already *have* a reference to that object!?
>>>def inplusplus(valu e,listObj):
... for i in listObj:
... if i is value:
... return value
... return False
...
def my_in(value, sequence):
if value in sequence:
return value
else:
return False

Ciao,
Marc 'BlackJack' Rintsch
Oct 22 '06 #2
Marc 'BlackJack' Rintsch wrote:
>>>>def inplusplus(valu e,listObj):
... for i in listObj:
... if i is value:
... return value
... return False
...

def my_in(value, sequence):
if value in sequence:
return value
else:
return False
however,
>>a = [1.0, 2, 3]
>>my_in(1, a)
1
>>my_in(2.0, a)
2.0
>>my_in(3L, a)
3L

so it all depends on what the OP means by "is in".

</F>

Oct 22 '06 #3
"Jorge Vargas" <jo**********@g mail.comwrote in message
news:ma******** *************** *************** @python.org...
Hi

I need to check if an object is in a list AND keep a reference to the
object I have done it this way but is there a better one?
>>>def inplusplus(valu e,listObj):
... for i in listObj:
... if i is value:
... return value
... return False
...
>>>l = [1,2,3,4]
print inplusplus(2,l)
2
>>>print inplusplus(9,l)
False
>>>print inplusplus(1,l)
1
>>>l.append(0 )
print inplusplus(0,l)
0
Just a couple of quick comments:
1. "if i is value" will check for identity, not equality. Your example with
small integers relies on a nonportable CPython implementation of using
cached objects. Check out this behavior:
>>def inplusplus(valu e,listObj):
.... for i in listObj:
.... if i is value:
.... return value
.... return False
....
>>a = 5
lst = [ 1,3,5,7 ]
inplusplus(5, lst)
5
>>inplusplus(a, lst)
5
>>lst.append( 123456789 )
inplusplus( 123456789,lst)
False

Instead of this loopy "is" test, just use "in":
>>def inplusplus(valu e,listObj):
.... if value in listObj: return value
.... return False
....
>>inplusplus( 123456789,lst)
123456789
2. What happens if "False" is in the list? How would you know?

-- Paul
Oct 22 '06 #4
Jorge Vargas wrote:
Hi

I need to check if an object is in a list AND keep a reference to the
object I have done it this way but is there a better one?
>def inplusplus(valu e,listObj):
... for i in listObj:
... if i is value:
... return value
... return False
...
>l = [1,2,3,4]
print inplusplus(2,l)
2
>print inplusplus(9,l)
False
>print inplusplus(1,l)
1
>l.append(0)
print inplusplus(0,l)
0
You mentioned a ist of objects.
The following example will return the actual object matched in the ist
allowing you to later change any mutable object returned and see the
change reflected in the list:
>>x = [[0], [1], [2]]
y = [1]
def inref(val, lst):
.... try:
.... return lst[ lst.index(val) ]
.... except ValueError:
.... return False
....
>>z = inref(y, x)
z
[1]
>>z[0] = 33
z
[33]
>>x
[[0], [33], [2]]
Hope this helps - Paddy.

Oct 23 '06 #5
Jorge Vargas <jo**********@g mail.comwrote:
>I need to check if an object is in a list AND keep a reference to the
object I have done it this way but is there a better one?
>>>def inplusplus(valu e,listObj):
... for i in listObj:
... if i is value:
... return value
... return False
...
try:
obj = listObj[listObj.index(v alue)]
# do something with obj
except ValueError:
# do whatever you're going to do if inplusplus returns False

Assuming you meant "if i == value" (as others have pointed out).

--
\S -- si***@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Oct 23 '06 #6
"Jorge Vargas" <jo**********@g mail.comwrites:
I need to check if an object is in a list AND keep a reference to the
object I have done it this way but is there a better one?
>def inplusplus(valu e,listObj):
... for i in listObj:
... if i is value:
... return value
... return False
That's bug-prone. Suppose the object's value is false (i.e. it's the
empty string, or None, or the boolean False, or whatever)? You're
best off raising an exception if the value is not found. You could
also do something like that using the list.index method.

Oct 23 '06 #7

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

Similar topics

7
22142
by: Alex | last post by:
I'm new to Oracle, so this question may sound silly. I have been given a list of Oracle tables (they may be views, I'm not sure) that are available to me. I can run simple SQL select statements against most of them in SQL Plus. But some of them have "slashes" in their names such as /XYZ/CUSTOMERS or /XYZ/ADDRESSES . When I try to use the name the way it's listed (with slashes) I get an error. I even tried replacing the slashes with dots,...
14
2031
by: Pedro Werneck | last post by:
Hi I have a class A, with metaclass M_A, and class B, subclass of A, with metaclass M_B, subclass of M_A. A class C, subclass of B must have M_B or a subclass of it as metaclass, but what if I need to 'disable' the code in M_B on C ? The correct way to do that seems to be with a M_C metaclass, subclass of M_B, implementing but not calling parent class methods, or calling 'type' methods.
43
2733
by: markryde | last post by:
Hello, I saw in some open source projects a use of "!!" in "C" code; for example: in some header file #define event_pending(v) \ (!!(v)->vcpu_info->evtchn_upcall_pending & \ !(v)->vcpu_info->evtchn_upcall_mask) whereas evtchn_upcall_pending is of type unsigned char (and also evtchn_upcall_mask is of type unsigned char).
5
4087
by: Nicolas Pontoizeau | last post by:
Hi, I am handling a mixed languages text file encoded in UTF-8. Theres is mainly French, English and Asian languages. I need to detect every asian characters in order to enclose it by a special tag for latex. Does anybody know if there is a unicode "table of character" implementation in python? I mean, I give a character and python replys me with the language in which the character occurs. Thanks in advance
4
3893
by: fran7 | last post by:
Hi, from help in the javascript forum I found the error in some code but need help. This bit of code works perfectly, trouble is I am writing it to a javascript function so the height needs to be in &quot;&quot; instead of "" otherwise I get an error message. Can anyone suggest how to write it so that it writes &quot; instead of "". I have tried all combinations of adding &quot; to the code but as soon as I think I am there I get throw out again. if...
350
11811
by: Lloyd Bonafide | last post by:
I followed a link to James Kanze's web site in another thread and was surprised to read this comment by a link to a GC: "I can't imagine writing C++ without it" How many of you c.l.c++'ers use one, and in what percentage of your projects is one used? I have never used one in personal or professional C++ programming. Am I a holdover to days gone by?
3
2584
dlite922
by: dlite922 | last post by:
Hey guys, My brains asleep and I don't know what's wrong with my session class. I'm over riding session with sesstion_set_save_handler() in a class; When in my member functions (open, close, read) I use "$this" I get the error "Using $this when not in object context". Here's my constructor:
5
1426
by: Muzammil | last post by:
i have problem with this operator "+" in doubly circular link list.(i think i have problem with return type). error is of instantiate error.(mean type dismatch) if any one can help me please reply. template <class T> DoublyCircularLinkList<TDoublyCircularLinkList<T>:: operator + (const DoublyCircularLinkList& rhs) { if (head==0 && rhs.head==0) {
15
3181
by: =?ISO-8859-15?Q?L=E9na=EFc?= Huard | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello all, For some reasons, somewhere in a program, I'd like, if possible, to quickly parse a whole file before rewinding it and letting the full analysis start. My problem is that the FILE* I want do parse has been fopen'ed far away from where I am and I don't know in which MODE my FILE* has been opened. And additionally, my FILE* may not be a regular file, but a continuous
0
8951
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9458
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
9317
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...
1
6743
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
6040
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
4555
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...
1
3266
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
2
2734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2184
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.