Index in a List
In Python, a list is a collection of items that are ordered and mutable (can be changed). Lists are created by placing items inside square brackets , and items in a list are separated by commas. Lists can store items of any data type, including numbers, strings, and other objects.
Index in a list refers to the position of an item in a list. Each item in a list has a unique index, which is a zero-based integer that indicates the position of the item in the list. The first item in the list has an index of 0, the second item has an index of 1, and so on.
You can access an item in a list using its index by using square bracket notation. For example:
numbers = [1, 2, 3, 4, 5, 6] print(numbers) # 3
In this example, the item at index 2 is accessed, which is 3.
You can also use the index to modify the value at that position, for example:
numbers = 9 print(numbers) # [1, 2, 9, 4, 5, 6]
In this example, the value at index 2 is modified to 9.
It’s important to note that, if you try to access an index that doesn’t exist in the list, it will raise an exception ‘IndexError: list index out of range’ .
Finding the index of an item in a list
In Python, you can use the ‘list.index(item)’ method to locate the index of an item in a list. The ‘index()’ method takes a single argument, which is the item you want to find the index of, and returns the index of the first occurrence of the item in the list.
numbers = [1, 2, 3, 4, 5, 6] index = numbers.index(4) print(index) # 3
In this example, the ‘index()’ method is used to find the index of the number 4 in the list ‘numbers’, and the result is 3 which is the index of the number 4 in the list.
If the item is not found in the list then it will raise an exception ‘ValueError: item is not in list’, to avoid this you can use ‘try-except’ block
try: index = numbers.index(7) print(index) except ValueError: print("item not found")
Alternatively, you can also use the ‘enumerate()’ function to get the index of an item in a list. The ‘enumerate()’ function returns an iterator that generates pairs of the form (index, item), where index is the index of the item in the list and item is the actual item.
numbers = [1, 2, 3, 4, 5, 6] for i, item in enumerate(numbers): if item == 4: print(i) # 3
In this example, the ‘enumerate()’ function is used to generate pairs of the form (index, item) for each item in the list ‘numbers’. The if statement is used to check if the current item is equal to 4, and if it is, the index of that item is printed.