Question 10 of 16beginner🔧 ApplyLong Answer3 marks

Write a function that returns the largest element of the list passed as parameter.

Correct Answer

python def findLargest(list1): largest = list1[0] for i in range(1, len(list1)): if list1[i] > largest: largest = list1[i] return largest

Example usage:

myList = [10, 45, 23, 78, 56] result = findLargest(myList) print("The largest element is:", result)

The function findLargest() takes a list as a parameter. It initializes the variable largest with the first element of the list. Using a for loop, it iterates through the remaining elements and compares each element with the current largest value.

If an element is greater than largest, the value of largest is updated. After checking all elements, the function uses the return statement to send back the largest element to the calling program.

Exercise: Programming Problems | Q: 3 | (Page 18)
For More Understanding

Explanation

This question tests the student's understanding of passing a list as a parameter to a function and implementing logic to find the maximum value. The solution follows the pattern shown in Program 9-1 and Program 9-4 from the textbook, where a list is passed as an argument to a function. The function iterates through the list elements using a loop and returns the result using the return statement.

Solution Steps

  1. Step 1: Define a function that accepts a list as parameter.

  2. Step 2: Initialize a variable 'largest' with the first element of the list.

  3. Step 3: Use a for loop to iterate through remaining elements of the list.

  4. Step 4: Compare each element with 'largest' and update if element is greater.

  5. Step 5: Return the largest element using the return statement.