Object in List : how?

Khairil Sitanggang ksit70 at gmail.com
Sat Jul 23 18:50:13 EDT 2022


Thank you.
I did it as you said. Yes, I forgot to create a new object Node() for each of the 3 instances.

The reason I wanted to do as I asked was that I expected Python provides that convenient feature (since it is a high level language). I use Matlab a lot and it is so rich of features that allow  us to process object array in many different ways.

Anyway, as I said, I just started playing with Python, and I like it so much. Thanks to Visual Studio Code making coding very enjoyable.



Get Outlook for iOS<https://aka.ms/o0ukef>
________________________________
From: Python-list <python-list-bounces+ksit70=gmail.com at python.org> on behalf of MRAB <python at mrabarnett.plus.com>
Sent: Saturday, July 23, 2022 4:57:34 PM
To: python-list at python.org <python-list at python.org>
Subject: Re: Object in List : how?

On 23/07/2022 05:28, Khairil Sitanggang wrote:
> Hello Expert:
>
> I just started using python. Below is a simple code.  I was trying to check
> if, say, NO1 is not in the NODELIST[:].NO
> How can I achieve this purpose?
>
> Regards,
> -Irfan
>
>
> class Node:
>      def __init__(self):
>          self.NO = 0
>          self.A = 20
>
> NODE = Node()
> NODELIST = []
>
> NODE.NO = 10
> NODELIST.append(NODE)
>
> NODE.NO = 20
> NODELIST.append(NODE)
>
> NODE.NO = 30
> NODELIST.append(NODE)
>
>
> NO1 = 20
> if NO1 not in NODELIST[:].NO  ???

No, you can't do it that way. You have to iterate through the list and
check each member individually:

     if any(NO1 == N.NO for N in NODELIST):

And another thing: you've created only 1 node, and you're changing it
each time before adding it to the list, so the list ends up with 3
references to the _same_ object.
--
https://mail.python.org/mailman/listinfo/python-list


More information about the Python-list mailing list