Python List

Common built-in list methods

These are some of the most frequently used built-in methods that operate on lists in Python. Let's explore what each one does:


  • len(list)

This method returns the length (number of elements) of a list. It's a quick way to determine how many items are in your list.

fruits = ["apple", "banana", "cherry"]
list_length = len(fruits)
print(list_length)  # Output: 3


  • min(list) and max(list)

These methods find the minimum and maximum elements within a list, respectively. They work with numbers and strings (based on alphabetical order for strings).

numbers = [3, 1, 4, 1, 5]
smallest = min(numbers)
largest = max(numbers)

print("Smallest:", smallest)  # Output: Smallest: 1
print("Largest:", largest)  # Output: Largest: 5


  • sort(list)

This method sorts the elements of a list in ascending order (from smallest to largest). It modifies the original list in place.

fruits = ["banana", "cherry", "apple"]
fruits.sort()
print(fruits)  # Output: ["apple", "banana", "cherry"]


  • reverse(list)

This method reverses the order of elements in place within the list. Imagine reversing the order of items in your shopping list.

fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits)  # Output: ["cherry", "banana", "apple"]


Important points to remember

  • sort() and reverse() modify the original list. If you want to preserve the original order, consider creating a copy of the list before using these methods.
  • min() and max() can work with different data types, but they might not behave as expected if you mix data types within a list.

It's time to take a quiz!

Test your knowledge and see what you've just learned.

What will be the output of the following code: fruits = ["apple", "banana", "cherry"]; list_length = len(fruits); print(list_length)?

3
2
1
0
Check Answer

What will be the output of the following code: numbers = [3, 1, 4, 1, 5]; print(min(numbers), max(numbers))?

1 5
1 4
3 5
4 5
Check Answer

What will fruits contain after executing: fruits = ["banana", "cherry", "apple"]; fruits.sort();?

["banana", "cherry", "apple"]
["apple", "banana", "cherry"]
["cherry", "banana", "apple"]
["apple", "banana", "cherry"]
Check Answer

What will fruits contain after executing: fruits = ["apple", "banana", "cherry"]; fruits.reverse();?

["cherry", "banana", "apple"]
["apple", "banana", "cherry"]
["banana", "cherry", "apple"]
["banana", "apple", "cherry"]
Check Answer

Which methods modify the original list?

min() and max()
len() and max()
min() and len()
sort() and reverse()
Check Answer