Home > database >  Python question what does this return entail
Python question what does this return entail

Time:09-01

Doing a leetcode problem #198 and was getting the question wrong even though on my end it was working and on paper, it was checking it out come to find out it was what I was returning.

My question is what does this mean return ans[len(nums)-1]

Edit: Thank you for the Help!

CodePudding user response:

return ans[len(nums)-1] can be broken into a number of different parts.

len(nums) - This will return the length of the variable nums.

-1 - The value from len(nums) will be subtracted by 1. This is likely done as adjustment due to lists starting counting from position 0 in Python.

ans[value] - this will return the item from the list ans in position value. This is calculated from len(nums) - 1

Finally return - This will return the value from a function so it can be used by the caller.

CodePudding user response:

If ans and nums are each a list/array or if nums is a string, it will return the result of the length of nums minus 1 in the [] which will pull that index from the ans list.

For example:

ans = [apple, orange, banana, strawberry, kiwi]
nums = [house, car, tree, cat] (it could be equal to a string "food" with same result)
return ans[len(nums)-1]
  • len(nums) is 4
  • minus 1
  • gives you ans[3]
  • which is strawberry
  • Related