Assigning variables confusion in Python 3 -
i thought understood how assignment works, after running these 2 pieces of code realized pretty confused now.
this in python 3.3:
numbers=[1,4,3] hello=numbers.reverse() print(hello) none
when print(numbers)
instead, [3,4,1]
expecting when printing hello
.
on example:
numbers='yeah' hello=numbers.capitalize() print(hello) yeah
how come when assigning list second variable, first example shows, none when printing second variable, when assigning string not happen? ran in python visualizer, still not answer question how/why is.
that's because numbers.reverse()
reverses list in place.
your code shoud be:
numbers=[1,4,3] numbers.reverse() print(numbers)
or if don't want modify original list numbers
, copy numbers hello:
from copy import copy numbers=[1,4,3] hello=copy(numbers) hello.reverse() print(hello)
the documentation of methods tell if method works in place (i.e. change object calling method on to), or if returns result
Comments
Post a Comment