Answer to first question:
In the first piece of code, Python raises a SyntaxError
because of this line: animals.pop()=value
. In Python, you assign a variable like this: x = 3
, where the variable name is on the left of the equals sign and the value you want to assign the variable to is on the right of the equals sign.
animals.pop()
is a function that returns the last item in the animals
list, so it cannot be a variable name. You've simply swapped the 2 sides of the equals sign. To make Python not throw an error you should replace that line with value = animals.pop()
, like you did in the third piece of code.
In the second piece of code, you simply spelled animals wrong (you spelled it like "aniamls", which caused a NameError
. You also assigned the return value of pets.append(value)
(which is None
, ie. not returning anything) to pets
setting the value of pets
to None
, which made Python evaluate pets.append(value)
in the second iteration of the for loop, and since pets is now None
, Python cannot call the function append
, a List
function on it.
Answer to second question:
The line for value in animals:
starts iteration through the list animals
, which basically means that you are running the code in the for loop for every value in animals, and the variable value
is assigned that value. Because you already have the value
variable from the for loop, you don't need to create a value variable inside the for loop. Also, a_list.pop()
returns the last value in a_list
, so it won't solve your problem anyways. If you would like more information on the pop()
function for a list, check out @mounika's answer.
The better way to solve your problem
The concise code you mentioned could be: pets = animals
. This essentially copies the value of the animals
variable into pets
. But, this actually aliases animals
to pets
, which basically makes changing pets
also change animals
in the same way, which you may not want. That's why something like pets = animals[:]
would be better, which makes a new variable pets
that has its values separate from the values of animals
. animals[:]
basically is a new value which is a list that contains all the items in the list animals
(essentially a copy of animals
).