Chapter 7: Problem 18
Describe the following list methods: a. index b. insert c. sort d. reverse
Short Answer
Expert verified
Question: Provide a brief explanation and example of the following Python list methods: index, insert, sort, and reverse.
Answer: The `index()` method finds the first occurrence of a specified element in a list and returns its index. For example, if we have a list `numbers = [1, 2, 3, 4, 3, 5]`, calling `numbers.index(3)` would return 2. The `insert()` method inserts a new element in a list at a specified index. For instance, if we have a list `fruits = ['apple', 'banana', 'cherry']`, calling `fruits.insert(1, 'orange')` would result in `['apple', 'orange', 'banana', 'cherry']`. The `sort()` method sorts a list in ascending order by default but can also be sorted in descending order using the `reverse` parameter. For example, a list `numbers = [3, 1, 5, 2, 4]` would become `[1, 2, 3, 4, 5]` after calling `numbers.sort()`, and `[5, 4, 3, 2, 1]` after calling `numbers.sort(reverse=True)`. The `reverse()` method reverses the order of elements in a list. For instance, a list `colors = ['red', 'green', 'blue', 'yellow']` would become `['yellow', 'blue', 'green', 'red']` after calling `colors.reverse()`.