How to find the largest number in a list Python using for loop | Code

  • by

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.

This process will go through the list length number of iteration and in the last temp value will be the largest number in a list.

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[0]

for i in numbers:
    if i > maxi:
        maxi = i
        
print("Greatest number: ", maxi)

Output:

How to find the largest number in a list Python using for loop

Or use this code (a bit complicated)

a = [18, 52, 23, 41, 32]

# variable to store largest number
ln = a[0] 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)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.