index(), count(), reverse(), sort()

Python List Methods: index()count()reverse()sort()

Let’s explore these essential list methods with multiple examples for each.

1. index() Method

Returns the index of the first occurrence of a value.

Examples:

python

# Example 1: Basic usage
fruits = ['apple', 'banana', 'cherry', 'banana']
print(fruits.index('banana'))  # Output: 1

# Example 2: With start parameter
print(fruits.index('banana', 2))  # Output: 3 (starts searching from index 2)

# Example 3: ValueError when not found
try:
    print(fruits.index('orange'))
except ValueError:
    print("Not found")  # Output: Not found

# Example 4: With start and end parameters
numbers = [1, 2, 3, 4, 3, 5]
print(numbers.index(3, 2, 5))  # Output: 4 (finds 3 between indexes 2-5)

2. count() Method

Returns the number of occurrences of a value.

Examples:

python

# Example 1: Basic count
numbers = [1, 2, 3, 1, 4, 1, 5]
print(numbers.count(1))  # Output: 3

# Example 2: Count with strings
words = ['a', 'the', 'a', 'an', 'the']
print(words.count('the'))  # Output: 2

# Example 3: Count with no matches
print(numbers.count(9))  # Output: 0

# Example 4: Count with nested lists (only counts top-level)
nested = [[1, 2], [3, 4], [1, 2]]
print(nested.count([1, 2]))  # Output: 2

3. reverse() Method

Reverses the elements of the list in place (modifies original).

Examples:

python

# Example 1: Basic reverse
nums = [1, 2, 3, 4]
nums.reverse()
print(nums)  # Output: [4, 3, 2, 1]

# Example 2: Reverse strings
colors = ['red', 'green', 'blue']
colors.reverse()
print(colors)  # Output: ['blue', 'green', 'red']

# Example 3: Reverse in place vs reversed()
original = [1, 2, 3]
# reversed() returns an iterator and doesn't modify original
print(list(reversed(original)))  # Output: [3, 2, 1]
print(original)  # Output: [1, 2, 3] (unchanged)

# Example 4: Reverse empty list
empty = []
empty.reverse()
print(empty)  # Output: [] (no error)

4. sort() Method

Sorts the list in place (modifies original).

Examples:

python

# Example 1: Basic sort
nums = [3, 1, 4, 2]
nums.sort()
print(nums)  # Output: [1, 2, 3, 4]

# Example 2: Reverse sort
nums.sort(reverse=True)
print(nums)  # Output: [4, 3, 2, 1]

# Example 3: Sort strings
fruits = ['banana', 'apple', 'cherry', 'date']
fruits.sort()
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'date']

# Example 4: Custom sort with key
words = ['apple', 'Banana', 'cherry', 'Date']
words.sort(key=str.lower)  # Case-insensitive sort
print(words)  # Output: ['apple', 'Banana', 'cherry', 'Date']

# Example 5: Sort vs sorted()
original = [3, 1, 2]
# sorted() returns new list and doesn't modify original
new_list = sorted(original)
print(new_list)  # Output: [1, 2, 3]
print(original)  # Output: [3, 1, 2] (unchanged)

Key Differences:

  • reverse() vs reversed(): One modifies in place, one returns new iterator
  • sort() vs sorted(): One modifies in place, one returns new list
  • index() raises ValueError if not found
  • count() returns 0 if no matches found

Similar Posts

  • append(), extend(), and insert() methods in Python lists

    append(), extend(), and insert() methods in Python lists, along with slicing where applicable. 1. append() Method Adds a single element to the end of the list. Examples: 2. extend() Method Adds multiple elements (iterable items) to the end of the list. Examples: 3. insert() Method Inserts an element at a specific position. Examples: Key Differences: Method Modifies List? Adds Single/Multiple Elements? Position append() ✅ Yes Single element (even if it’s a list) End…

  • Basic Character Classes

    Basic Character Classes Pattern Description Example Matches [abc] Matches any single character in the brackets a, b, or c [^abc] Matches any single character NOT in the brackets d, 1, ! (not a, b, or c) [a-z] Matches any character in the range a to z a, b, c, …, z [A-Z] Matches any character in the range A to Z A, B, C, …, Z [0-9] Matches…

  • math Module

    The math module in Python is a built-in module that provides access to standard mathematical functions and constants. It’s designed for use with complex mathematical operations that aren’t natively available with Python’s basic arithmetic operators (+, -, *, /). Key Features of the math Module The math module covers a wide range of mathematical categories,…

  • Python Installation Guide: Easy Steps for Windows, macOS, and Linux

    Installing Python is a straightforward process, and it can be done on various operating systems like Windows, macOS, and Linux. Below are step-by-step instructions for installing Python on each platform. 1. Installing Python on Windows Step 1: Download Python Step 2: Run the Installer Step 3: Verify Installation If Python is installed correctly, it will…

  • How to create Class

    🟥 Rectangle Properties Properties are the nouns that describe a rectangle. They are the characteristics that define a specific rectangle’s dimensions and position. Examples: 📐 Rectangle Methods Methods are the verbs that describe what a rectangle can do or what can be done to it. They are the actions that allow you to calculate information…

  • The print() Function

    The print() Function Syntax in Python 🖨️ The basic syntax of the print() function in Python is: Python Let’s break down each part: Simple Examples to Illustrate: 💡 Python Basic print() Function in Python with Examples 🖨️ The print() function is used to display output in Python. It can print text, numbers, variables, or any…

Leave a Reply

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