Back to course

List Methods for Searching, Counting, and Sorting

Python Programming: The 0 to Hero Bootcamp

Useful List Methods

1. Searching (.index() and in)

  • .index(value): Returns the index of the first occurrence of the specified value. Raises a ValueError if the item is not found.
  • in keyword: Used to quickly check if an item exists (returns True or False).

python numbers = [10, 20, 30, 20, 40]

Using index

position = numbers.index(30) print(f"30 is at index: {position}") # Output: 2

Using 'in' keyword

if 50 in numbers: print("50 is present") else: print("50 is missing")

2. Counting (.count())

Returns the number of times a specified value appears in the list.

python counted = [1, 2, 2, 3, 2, 4] count_twos = counted.count(2) print(f"Number of 2s: {count_twos}") # Output: 3

3. Sorting (.sort() and sorted())

  • .sort(): Sorts the list in place (modifies the original list). Returns None.
  • sorted(list): Returns a new sorted list, leaving the original list unchanged.

python data = [5, 1, 4, 2, 8]

In-place sort

data.sort() print(f"In-place sort: {data}") # [1, 2, 4, 5, 8]

Reverse sort (only for .sort())

data.sort(reverse=True) print(f"Reverse sort: {data}") # [8, 5, 4, 2, 1]

Non-destructive sort

original = [10, 50, 20] new_sorted = sorted(original) print(f"Original list: {original}") # [10, 50, 20] print(f"New sorted list: {new_sorted}") # [10, 20, 50]