Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initializing a variable while indexing a list in python

I am trying to debug some old code and need to understand a specific line of code, but it keeps giving errors so I can’t see exactly what is going on. I will simplify it here.

I have two lists: A and B

A = [0,1,2,3]
B = [5,6,7,8]

My question is: Is there any difference between the two snippets of code below?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

A[B==0] = 11

or

A[0] = 11

Would initializing list B to 0 while indexing list A be any different than just indexing list A with 0?

>Solution :

To answer your question: A[B==0] and A[0] are in this case equivalent, because B==0 is false.

However, you aren’t initializing list B to 0, you’re comparing it. A[B==0] does not change the value of B. To assign to B in A‘s indexer, you’d need to use the walrus operator, A[B:=0] (which would also be equivalent to A[0]).

Your question implies or invites misunderstanding as it looks to assert that B==0 is initialization/assignment, so I might suggest reviewing the wording of the question for clarity.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading