PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

[FIXED] Why does this code fail? assigning variable to list of itself in for loop

 July 10, 2022     immutability, python, reference, variable-assignment, variables     No comments   

Issue

a = 'hello'
b = None
c = None
for x in [a, b, c]:
    if isinstance(x, (basestring, dict, int, float)) or x is None:
        x = [x]
a

returns 'hello', but expected ['hello']. However, this works:

a = 'hello'
a = [a]
a

returns ['hello'].


Solution

To achieve that, first you have to understand that you have two diferent refecerences, a and x (for each element), and the reference for the list [a,b,c], used only in the for loop, and never more.

To achieve your goal, you could do this:

a = 'hello'
b = None
c = None
lst = [a, b, c] #here I create a reference for a list containing the three references above
for i,x in enumerate(lst):
    if isinstance(x, (str,dict, int, float)) or x is None: #here I used str instead basestring
        lst[i] = [x]

print(lst[0]) #here I print the reference inside the list, that's why the value is now showed modified

['hello']

but as I said, if you do print(a) it will show again:

'hello' #here i printed the value of the variable a, wich has no modification

because you never did anything with it.

Take a look at this question to understand a little more about references How do I pass a variable by reference?



Answered By - Damian Lattenero
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing