Object in List : how?

Dennis Lee Bieber wlfraed at ix.netcom.com
Sat Jul 23 16:55:28 EDT 2022


On Fri, 22 Jul 2022 23:28:11 -0500, Khairil Sitanggang <ksit70 at gmail.com>
declaimed the following:


>class Node:
>    def __init__(self):
>        self.NO = 0
>        self.A = 20
>
>NODE = Node()
>NODELIST = []
>

	Comment...

	The convention is that ALL CAPS is used to indicate something that is
to be treated as a CONSTANT. Classes get capitalized initial letters. Names
of variable data is traditionally all lower case, lower case with _ between
"words" (eg: lower_case), or camel case (eg: camelCase).

>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  ???

	The [:], in this statement, just says "make a copy of nodelist". The
/list/ does not have an attribute named "NO". You have to ask for each
element IN the list.

	One convoluted way (I've not tested it) is:

	if len([node for node in nodelist if node.no == no1]):
		print("Found at least one occurence")

	This is a list comprehension; it loops over each element in nodelist,
making a new list if the element attribute matches the criteria. Python
treats 0 as "false" and if no element matched, the list created is empty,
so len() is 0. Anything else implies a match was found.


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


More information about the Python-list mailing list