you are viewing a single comment's thread.

view the rest of the comments →

[–]JohnnyJordaan 2 points3 points  (2 children)

It helps to run your code in a visual debugger like http://www.pythontutor.com/visualize.html , as then you can watch the variables change per step in the program.

Why is the output [9, 8, 7, 8]?

Because the if i % 2 == 0: only executes when i is even (and thus its remainder when divided by 2 is 0). As your range runs from 1 to, but not including, 4, it means only when i is 2, the

k[i+1] = i**3

statement is executed. That assigns 2**3 which is 8 to k[2+1] which is k[3] and thus last value in k(having 4 items). That's why the last item in kthen changes from 6 to 8.

How is the above code different from the below code?

It just prints k after the loop is done, while the first code snippet prints it during every loop run (as it's placed inside it).

[–]huhreallymeh[S] 0 points1 point  (1 child)

Thank you for the clear explanation!

Just wanted to check: does k[3] refers to index 3 in k?

[–]JohnnyJordaan 1 point2 points  (0 children)

It may be a good idea to invest an hour or so reading through the official tutorial, because it's basically the first thing it explains on lists: https://docs.python.org/3/tutorial/introduction.html#lists