Python list question #148879
Replies: 7 comments 13 replies
-
You can iterate through the list and keep track of the maximum value found so far. Here's a simple way to do it: def find_largest(numbers):
if not numbers:
raise ValueError("The list is empty")
largest = numbers[0] # Assume the first element is the largest initially
for num in numbers:
if num > largest:
largest = num
return largest You can test it like this: # Example usage:
numbers_list = [3, 5, 7, 2, 8, -1, 4]
largest_number = find_largest(numbers_list)
print("The largest number is:", largest_number) If that works for you, could you please mark my answer as accepted? Thanks |
Beta Was this translation helpful? Give feedback.
-
Your next turn is to make a sort of this list! |
Beta Was this translation helpful? Give feedback.
-
There are actually several ways to achieve your goal.JustADeni gave an example, but I don't prefer it as it compares the first value twice (leading to one unnecessary iteration).Here are two possible implementations, but note there are many ways to do this. def find_largest(list):
if not list:
raise ValueError("The list is empty")
max = list[0]
for i in range(1, len(list)):
if list[i] > max:
max = list[i]
return max Or def find_largest(list):
if not list:
raise ValueError("The list is empty")
max = 0
for i in range(1, len(list)):
if list[i] > list[max]:
max = i
return list[max] If this works for you, could you please mark my answer as accepted? Thanks! |
Beta Was this translation helpful? Give feedback.
-
One with the least number of characters:def find_largest(nums):
return min(nums,key=-int) PS: If this works for you, could you please mark my answer as accepted? Thanks! 😊 |
Beta Was this translation helpful? Give feedback.
-
🔹 Finding the Largest Number in a List (Without
|
Beta Was this translation helpful? Give feedback.
-
Well this does the job using two loops. |
Beta Was this translation helpful? Give feedback.
-
🔹 Finding the Largest Number in a List (Without
|
Beta Was this translation helpful? Give feedback.
-
How do you find the largest number in a list of integers in Python without using the max() function?
Beta Was this translation helpful? Give feedback.
All reactions