Empty list is interpreted as a string
HINT: This error is caused by what you do to your
new_val variable. Check all your commands and you shall find the cause for the error.
I understood it’s due to new_val variable. I got to know the system assuming that as a string instead of a list.
I’m trying to understand why the system interprets new_val as str when I declared that as “new_val = ” empty list
Why? Because Python is dynamically typed language. I.e., you can declare variable of one type (
list), but when you assign it string value, it will be of
What happens AFTER you declare your
Yes that’s correct. Now either I have to do one of the following
- Return a list value
- Convert this string to a list
But when I’m trying to convert the string to a list i’m receiving the word only, for eg: “a_string” is converted as “a”,"_",“s”,“t”,“r”,“i”,“n”,“g”.
I understood string is considered to be list of lists. I’m trying to achieve is something to have the original value but in the list type and append the new value at the end of the list
This might sound very easy for some but actually this type of error touches a very important concept in programming. I learnt programming with Ruby and one concept that you can transfer to Python is the fact that variables can be considered as pointers.
In a language like C you need to define pointers which are tools that basically indicate where in the memory the object / value is going top be stored. Variables play a somewhat similar role here.
So when you initialize your
new_val and assigns to it a list, this variable points to a list object. In the following line you re-assign this variable to a new object, a string. Consequently when you invoke the
append method on it Python throw an error because the variable points to a string object which does not have the
A very easy way to circumvent this is to rename your variable. Variable naming is a very important topic in programming. Try using
new_val_1 =  new_val_2 = change_name(a_string)
And then change the rest of the code accordingly.
I guess this should work now.