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

  • What is PyCharm? Uses, History, and Step-by-Step Installation Guide

    What is PyCharm? PyCharm is a popular Integrated Development Environment (IDE) specifically designed for Python development. It is developed by JetBrains and is widely used by Python developers for its powerful features, ease of use, and support for various Python frameworks and tools. PyCharm is available in two editions: Uses of PyCharm PyCharm is a…

  • date time modules class55

    In Python, the primary modules for handling dates and times are: 🕰️ Key Built-in Modules 1. datetime This is the most essential module. It provides classes for manipulating dates and times in both simple and complex ways. Class Description Example Usage date A date (year, month, day). date.today() time A time (hour, minute, second, microsecond,…

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”—the regex engine looks ahead in the string to see if the pattern inside…

  • sqlite3 create table

    The sqlite3 module is the standard library for working with the SQLite database in Python. It provides an interface compliant with the DB-API 2.0 specification, allowing you to easily connect to, create, and interact with SQLite databases using SQL commands directly from your Python code. It is particularly popular because SQLite is a serverless database…

  • List of machine learning libraries in python

    Foundational Libraries: General Machine Learning Libraries: Deep Learning Libraries: Other Important Libraries: This is not an exhaustive list, but it covers many of the most important and widely used machine learning libraries in Python. The choice of which library to use often depends on the specific task at hand, the size and type of data,…

  • re module

    The re module is Python’s built-in module for regular expressions (regex). It provides functions and methods to work with strings using pattern matching, allowing you to search, extract, replace, and split text based on complex patterns. Key Functions in the re Module 1. Searching and Matching python import re text = “The quick brown fox jumps over the lazy dog” # re.search()…

Leave a Reply

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