python - explain the print strategy in below codes -
i started learning python , while using lists faced problem.
here assigned movie names variable movies
:
>>> movies = ["dragon","dragon warrior","kungfu","kungfu panda"]
after assigning, used print
command execute it:
>>> print(movies)
the output below:
['dragon', 'dragon warrior', 'kungfu', 'kungfu panda']
in same way, when started using for-loop in lists same print
command, output entirely different. can't understand how changed because of for-loop:
>>> fav_movie in movies: print(fav_movie)
output:
dragon dragon warrior kungfu kungfu panda
why same print command working differently?
print(movies)
prints str
version of list object, while in loop you're printing str
version of individual items inside list.
>>> print(movies) ['dragon', 'dragon warrior', 'kungfu', 'kungfu panda']
is equivalent to:
>>> print(movies.__str__()) #or print(str(movies)) ['dragon', 'dragon warrior', 'kungfu', 'kungfu panda']
note you're seeing quotes here in list elements, that's because representation used repr
version of objects. repr
version of list contain quotes around it.
>>> repr(movies) "['dragon', 'dragon warrior', 'kungfu', 'kungfu panda']"
repr
computer friendly output , str
human friendly, example floats:
>>> x = 1.1 + 2.2 >>> print repr(x) 3.3000000000000003 >>> print str(x) 3.3
also note string returned repr
can re-used generate object using eval
.
for more details read: difference between str , repr in python.
inside loop you're printing str
version of each item:
>>> print(movies[0]) dragon >>> print(movies[0].__str__()) dragon >>> movie in movies: ... print(str(movie)) ... dragon dragon warrior kungfu kungfu panda
Comments
Post a Comment