Better way to set values of list

Viewed 61
def max_end3(nums):
    for i in range(len(nums)):
        if nums[0] > nums[2]:
            nums[0] = nums[0]
            nums[1] = nums[0]
            nums[2] = nums[0]
            return nums
        elif nums[2] > nums[0]:
            nums[0] = nums[2]
            nums[1] = nums[2]
            nums[2] = nums[2]
            return nums
        elif nums[0] == nums[2]:
            nums[0] = nums[0]
            nums[1] = nums[0]
            nums[2] = nums[0]
            return nums

The task was to replace all items of a list with either the first or last index depending on which is greater. I got the answer correct but is there a shorter and more efficient way of writing this code?

2 Answers

You've got repeated logic. That is, in each of the three if clause blocks, you're setting all three locations equal to a particular value and then returning nums. Furthermore, you're using an if block to determine which of the two values is larger. The built-in function max will do this for you. So,

def max_end3(nums):
    max_value = max(nums[0], nums[2])
    for i in range(3):
        nums[i] = max_value
    return nums

Based on your code, you only really need to return a list of len(nums) numbers, of value max(nums):

def max_end3(nums):
    return [max(nums[0], nums[-1])]*len(nums)
Related