Python List

Python program to find largest and smallest number in a list

Description: Write a Python program to find the largest and the smallest number in a list.

Rules and hints:

  • First use the built-in max() and min() functions.
  • Then do it with a loop, without these functions.

Python program to find the largest and smallest number in a list

numbers = [45, 12, 89, 3, 67]

print("Largest:", max(numbers))
print("Smallest:", min(numbers))

largest = smallest = numbers[0]
for n in numbers:
    if n > largest:
        largest = n
    if n < smallest:
        smallest = n

print("Loop result:", largest, smallest)

Output:

Tutorials Class - Output Window

Largest: 89
Smallest: 3
Loop result: 89 3

How it works

  • max() and min() check the whole list for you.
  • In the loop we start with the first item as both largest and smallest, and update them when a bigger or smaller item comes.

Learn more in Python Lists.

Python program to remove duplicates from a list

Description: Write a Python program to remove the duplicate items from a list.

Rules and hints:

  • A set keeps only unique values, but it does not keep the order.
  • dict.fromkeys() keeps the order of the first appearance.

Python program to remove duplicates from a list

items = [1, 2, 2, 3, 4, 4, 5]

unique_sorted = sorted(set(items))
unique_ordered = list(dict.fromkeys(items))

print(unique_sorted)
print(unique_ordered)

Output:

Tutorials Class - Output Window

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]

How it works

  • set(items) removes the duplicates, and sorted() makes a sorted list of it.
  • A dictionary cannot have duplicate keys, and in Python 3.7+ it keeps the insertion order. So dict.fromkeys(items) followed by list() keeps the first order.

Related: Python Sets and Python Dictionary.