Skip to content

Commit 6779331

Browse files
[Edit] Python Lists .index() (#6974)
* [Edit] SQL: DATEDIFF() * Update datediff.md * [Edit] Python Lists `.index()` * Update content/python/concepts/lists/terms/index/index.md * Update content/python/concepts/lists/terms/index/index.md * Update content/python/concepts/lists/terms/index/index.md ---------
1 parent 81bacdd commit 6779331

File tree

1 file changed

+118
-22
lines changed
  • content/python/concepts/lists/terms/index

1 file changed

+118
-22
lines changed
Lines changed: 118 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,150 @@
11
---
22
Title: '.index()'
3-
Description: 'Finds the first occurrence of a particular value within the list.'
3+
Description: 'Returns the index of the first occurrence of a specified element in a list.'
44
Subjects:
5-
- 'Data Science'
65
- 'Computer Science'
6+
- 'Data Science'
77
Tags:
8+
- 'Index'
89
- 'Lists'
910
- 'Methods'
11+
- 'Search'
1012
CatalogContent:
1113
- 'learn-python-3'
12-
- 'paths/data-science'
1314
- 'paths/computer-science'
1415
---
1516

16-
Finds the first occurrence of a particular value within the list.
17+
The **`.index()`** method is a [built-in](https://www.codecademy.com/resources/docs/python/built-in-functions) Python [list](https://www.codecademy.com/resources/docs/python/lists) method that returns the index position of the first occurrence of a specified element within a list. This method performs a sequential search through the list from left to right, making it an essential tool for locating elements when you need to know their exact position rather than just their presence. The method works with any data type that can be stored in a list, including strings, numbers, booleans, and even other lists or objects.
18+
19+
The `.index()` method is commonly used in data processing, search algorithms, and list manipulation tasks. It's particularly useful when working with ordered data where position matters, such as finding the location of a specific item in a menu system, locating a particular record in a dataset, or determining the position of an element before performing operations like insertion or deletion. Unlike the `in` operator which only returns a boolean value, `.index()` provides the exact numerical position needed for precise list operations.
1720

1821
## Syntax
1922

23+
```pseudo
24+
list.index(element, start, end)
25+
```
26+
27+
**Parameters:**
28+
29+
- `element`: The item to search for in the list. This parameter is required and can be of any data type.
30+
- `start` (optional): The index position to start the search. Defaults to 0 if not specified.
31+
- `end` (optional): The index position to end the search at (exclusive). Defaults to the length of the list if not specified.
32+
33+
**Return value:**
34+
35+
The `.index()` method returns an integer representing the index position of the first occurrence of the specified element within the search range. If the element is not found, the method raises a [`ValueError`](https://www.codecademy.com/resources/docs/python/errors) exception.
36+
37+
## Example 1: Basic Index Search
38+
39+
This example demonstrates the fundamental usage of the `.index()` method to find the position of an element in a simple list:
40+
2041
```py
21-
list.index(value, start, end)
42+
# Create a list of programming languages
43+
languages = ['Python', 'JavaScript', 'Java', 'C++', 'Ruby']
44+
45+
# Find the index of 'Java'
46+
java_index = languages.index('Java')
47+
print(f"Java is at index: {java_index}")
48+
49+
# Find the index of the first element
50+
first_language = languages.index('Python')
51+
print(f"Python is at index: {first_language}")
2252
```
2353

24-
The `.index()` list method has three parameters:
54+
This example results in the following output:
2555

26-
- `value`: The string to search for. (Required)
27-
- `start`: The index to start the search. Default is index 0.
28-
- `end`: The position to end the search. Default is end of the string.
56+
```shell
57+
Java is at index: 2
58+
Python is at index: 0
59+
```
2960

30-
## Example 1
61+
The method successfully locates 'Java' at index position two and 'Python' at index position 0, demonstrating how Python uses zero-based indexing, where the first element is at position 0.
3162

32-
To find the index the first `'pen'` within the `backpack` list:
63+
## Example 2: Finding Items in Student Grade Records
3364

34-
```codebyte/python
35-
backpack = ['pencil', 'pen', 'notebook', 'textbook', 'pen', 'highlighter', 'pen']
65+
This example shows a real-world scenario where `.index()` helps locate specific student records in an educational system for grade processing:
66+
67+
```py
68+
# Student names in order of enrollment
69+
students = ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Frank']
70+
71+
# Grades corresponding to each student
72+
grades = [92, 85, 78, 95, 88, 91]
3673

37-
firstPen = backpack.index('pen')
74+
def get_student_grade(student_name):
75+
try:
76+
# Find the student's position in the list
77+
student_index = students.index(student_name)
78+
# Use that position to get their grade
79+
return grades[student_index]
80+
except ValueError:
81+
return f"Student {student_name} not found in records"
3882

39-
print(firstPen)
40-
# Output: 1
83+
# Check grades for different students
84+
print(f"Charlie's grade: {get_student_grade('Charlie')}")
85+
print(f"Diana's grade: {get_student_grade('Diana')}")
86+
print(f"Unknown student: {get_student_grade('Sam')}")
4187
```
4288

43-
## Example 2
89+
This example results in the following output:
4490

45-
To find the index the first `'pen'` within the `backpack` list within index 3 to index 6:
91+
```shell
92+
Charlie's grade: 78
93+
Diana's grade: 95
94+
Unknown student: Student Sam not found in records
95+
```
96+
97+
This demonstrates how `.index()` can be used to correlate data between parallel lists and handle cases where the searched element doesn't exist by using try-except error handling.
98+
99+
## Codebyte Example: Inventory Management with Search Range
100+
101+
This example illustrates a warehouse inventory system where `.index()` with start and end parameters helps locate items within specific storage sections:
46102

47103
```codebyte/python
48-
backpack = ['pencil', 'pen', 'notebook', 'textbook', 'pen', 'highlighter', 'pen']
104+
# Warehouse inventory with repeated items in different sections
105+
inventory = ['laptop', 'mouse', 'keyboard', 'laptop', 'monitor', 'laptop', 'headset']
106+
107+
def find_item_in_section(item, section_start=0, section_end=None):
108+
try:
109+
if section_end is None:
110+
section_end = len(inventory)
49111
50-
firstPen = backpack.count('pen', 3, 6)
112+
# Search for item within specified section
113+
item_position = inventory.index(item, section_start, section_end)
114+
return f"Found {item} at position {item_position}"
115+
except ValueError:
116+
return f"{item} not found in specified section"
51117
52-
print(firstPen)
53-
# Output: 4
118+
# Find laptop in different warehouse sections
119+
print("Searching entire warehouse:")
120+
print(find_item_in_section('laptop'))
121+
122+
print("\nSearching from position 2 onwards:")
123+
print(find_item_in_section('laptop', 2))
124+
125+
print("\nSearching between positions 4-6:")
126+
print(find_item_in_section('laptop', 4, 6))
127+
128+
print("\nSearching for headset in early section (positions 0-3):")
129+
print(find_item_in_section('headset', 0, 3))
54130
```
131+
132+
This example shows how the start and end parameters allow you to search within specific ranges of a list, which is useful for sectioned data or when you need to find subsequent occurrences of an element.
133+
134+
## Frequently Asked Questions
135+
136+
### 1. What happens if the element appears multiple times in the list?
137+
138+
The `.index()` method always returns the index of the first occurrence of the element. If you need to find all occurrences, use a list comprehension with `enumerate()` or implement a custom search function.
139+
140+
### 2. Can I use `.index()` with different data types?
141+
142+
Yes, `.index()` works with any data type stored in a list, including strings, numbers, booleans, lists, tuples, and custom objects. The method uses equality comparison (`==`) to find matches.
143+
144+
### 3. Is there a performance difference between `.index()` and other search methods?
145+
146+
In the worst case, the `.index()` method has `O(n)` time complexity, as it may need to check every element. Consider using dictionaries or other data structures that offer faster lookup times for frequently repeated searches on large lists.
147+
148+
### 4. Is the `.index()` method case-sensitive?
149+
150+
Yes, when used with strings, `.index()` performs a case-sensitive comparison. `'Python'.index('p')` would raise a `ValueError`, while `'Python'.index('P')` would return `0`.

0 commit comments

Comments
 (0)