0
Can someone explain this simple Python code?
3 Answers
0
First You got declaration of a list of names. This list has len(names) elements - since len() is a function giving the size/number of elements in the list.
i is the index. In lists You start indexing with 0(first element has index of 0). In this example index begins as sub-last element.
Then You have while loop which prints the name from the list on which index points, then decreese the index by one until it will be equal to 0.
Tldr: this code prints out reversed list of names, skipping the last name from original list.
0
Thanks for answering
But how about if i want to print the last name as well? And why is it reversed?
Thank you again
0
for Your list:
names = ["dottie" , "ed" , "sally" , "ned" , "barb" , "robert" , "mary" , "oscar" , "alice" , "wimpy"]
names[0] is dottie
names[1] is ed
...
names[len(names)-1] is the last name - wimpy.
To print all of them from the first to last, You have to start with 0 index and loop over all of them:
i = 0
while (i<len(names)):
print(names[i])
i = i+1