Understand code


Can you please explain this code i am not understanding it.

What parts don’t you understand? You can add in some print() statements to visualize things that may be unclear:

def append_sum(lst):
  print('lst[-1] is: ', lst[-1])
  print('lst[-2] is: ', lst[-2])
  lst.append(lst[-1] + lst[-2])
  print('lst is now: ', lst)
  print('lst[-1] is: ', lst[-1])
  print('lst[-2] is: ', lst[-2])
  lst.append(lst[-1] + lst[-2])
  print('lst is now: ', lst)
  print('lst[-1] is: ', lst[-1])
  print('lst[-2] is: ', lst[-2])
  lst.append(lst[-1] + lst[-2])
  print('lst is now: ', lst)
  return lst

print(append_sum([1, 1, 2]))

I didn’t understand why we used this1st[-1] + 1st[-2]

It’s lst not 1st. lst is the parameter for the function append_sum. The argument supplied for that parameter is found in this line:

print(append_sum([1, 1, 2]))
# argument       ^^^^^^^^^

The argument is a list, so inside the function lst is assigned to [1, 1, 2].

Did you try running the code I provided with the extra print()'s?

Ok I understood thanks

1 Like