简体   繁体   中英

Print list backwards in Python

I know there are better ways to print things backwards. But for some reason I can't get this to work. Any ideas why?

fruit = 'banana'
index = 0
while index < len(fruit):
    print fruit[-(index)]
    index = index + 1

You reversed everything but the b , because you started at 0, and -0 is still 0.

You end up with the indices 0, -1, -2, -3, -4, -5, and thus print b , then only anana in reverse. But anana is a palindrome, so you cannot tell what happened! Had you picked another word it would have been clearer:

>>> fruit = 'apple'
>>> index = 0
>>> while index < len(fruit):
...     print fruit[-index]
...     index = index + 1
... 
a
e
l
p
p

Note the a at the start, then pple correctly reversed.

Move the index = index + 1 up a line:

index = 0
while index < len(fruit):
    index = index + 1
    print fruit[-index]

Now you use the indices -1, -2, -3, -4, -5 and -6 instead:

>>> fruit = 'banana'
>>> index = 0
>>> while index < len(fruit):
...     index = index + 1
...     print fruit[-index]
... 
a
n
a
n
a
b
>>> fruit = 'apple'
>>> index = 0
>>> while index < len(fruit):
...     index = index + 1
...     print fruit[-index]
... 
e
l
p
p
a

I removed the (..) in the expression -(index) as it is redundant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM