Use temp variable and if statement to find the largest number in a list Python using for loop. Writing your own logic is easy, use temp variable to assign the first value of the list then swap it with the next large number.
How to find the largest number in a list Python using for loop example
Simple example code
numbers = [1, 2, 3, 5, 9, 6, 101, 88, 66, 6, 101, 55, -1001] maxi = numbers for i in numbers: if i > maxi: maxi = i print("Greatest number: ", maxi)
Or use this code (a bit complicated)
a = [18, 52, 23, 41, 32] # variable to store largest number ln = a if a else None # find largest number for i in a: if i > ln: ln = i print("Largest element is: ", ln)
Output: Largest element is: 52
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.