Bài toán: cho danh sách, tính phần tử lớn nhất.
Cách 1: Dùng sort()
list1 = [23, 1, 32, 67, 2, 34, 12]
list1.sort()
print("Largest element is:", list1[-1])
Largest in given array is 67
Cách 2: Dùng max()
list1 = [23, 1, 32, 67, 2, 34, 12]
print("Largest element is:", max(list1))
Largest in given array is 67
Nhập từ người dùng
list1 = []
num = int(input("Enter number of elements in list: "))
for i in range(1, num + 1):
ele = int(input("Enter elements: "))
list1.append(ele)
print("Largest element is:", max(list1))
Kết luận
Đã học cách lấy phần tử lớn nhất: sort() hoặc max() (khuyên dùng).