Answer: To find the index of an element by using ‘for loop’ we can use the index() function which returns the position of the element.
In Python, for loops are used to search for multiple occurrences of an element in a data type. In this case, you can use a for loop to access the index of the required element. Let’s check out some examples to get an idea about getting index values using a for-loop in Python.
Table of Contents:
Methods to Access Index Values using a For Loop
Python provides various methods in its built-in libraries that can be used to access index values of a data type. Following are some of these methods:
Method 1: Accessing the Index Values using for-loop with index() Method in Python
The index() method is used to find the specific position of an element within a list. It returns the index of the first occurrences of the value, helping you locate its position. If the value is not found it returns ValueError.
Example:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Create a list of even numbers
even_numbers = [ ]
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
even_numbers.append(numbers[i])
# Finding the index of 7 in the list
index_of_seven = numbers.index(7)
# Printing the results
print(f"Even numbers: {even_numbers}")
print(f"The index of 7 in the list is: {index_of_seven}")
Output:
Here, the code creates a list of even numbers from numbers, using ‘for-loop’ it appends the elements that are divisible by 2. Using the index() function it prints both the even numbers and the index of 7.
Method 2: Accessing both Index and Value using For-loop with enumerate() method in Python
In Python, the enumerate() method will give the both index and the value. Similar to the Index method, if the index is found, it returns the first index of the element where it appears, and if the index is not found it raises a ValueError.
Example:
subjects = ['Telugu', 'English', 'Hindi', 'Science']
# Using enumerate() to access both index and value
print("accessing the elements as per index:")
for index, subject in enumerate(subjects):
print(f’index {index} contains {subject}')
Output:
Here the subject will hold values like (‘Telugu’, ‘English’, ‘Hindi’, and ‘Science’) at the current index. In the last line, we have used the f’ index {index} contains {subject} string that prints the index and subject name.
Method 3: Accessing the Index and Value using for-loop with range() method in Python
If we are working with external lists we should get more control over indices by using the range() function. The range() function in Python generates the sequence of numbers which is very useful in a for-loop where you need to iterate a sequence of integers.
Example:
subjects = ['Telugu', 'English', 'Hindi', 'Science']
print("Accessing the elements by using range :")
for i in range(len(subjects)):
print(f'Index {i} contains {subjects[i]}')
Output:
Note: range(len(fruits)): This generates indices from 0 to the length of the list. In the range() function also the starting index starts with 0 by default and stops before a specified number.
Method 4: Accessing the Index and Value using for-loop with Conditional Check method in Python
This condition is useful when we want to find the index of specific items. By applying the for-loop we can access the index and value by specifying the necessary condition.
Example:
subjects = ['Telugu', 'English', 'Hindi', 'Telugu', 'Science', 'Telugu']
# Find all indices where 'Telugu' appears
indices_of_Telugu = []
for i, subject in enumerate(subjects):
if subject == 'Telugu':
indices_of_Telugu.append(i)
print(f"Indices of 'Telugu': {indices_of_Telugu}")
Output:
Note: As per the specified condition mentioned in the program if subject == ‘Telugu’, if the value is ‘Telugu’, we append the index to the list indices_of_Telugu.
Method 5. Accessing both Index and Value using for-loop with zip() in Python
The zip() method in Python is used to combine multiple iterables (tuples, lists) into a single iterator of the tuple. Each tuple contains an element from the input iterable sharing the same index and position.
Example:
# Assigning the lists
list1 = ['a', 'b', 'c', 'd']
list2 = [4, 5, 6, 8]
# Using zip() to combine lists
for idx, items in zip(range(len(list1)), zip(list1, list2)):
print(f"Index: {idx}, List1 Item: {items[0]}, List2 Item: {items[1]}")
Output:
Here, the zip() method is used to combine both lists and make them as pairs. range(len(list1)) is used to generate the index values, which are used inside the loop.
The itertools moduleprovides various tools for the iterators. Using the itertools.count() method, the elements can be iterated along with their indexes.
Example:
import itertools
list1 = ['apple', 'banana', 'cherry']
print("Accessing the index and element:")
# Using itertools.count() to manually generate indices
for idx, fruit in zip(itertools.count(), list1):
print(f"Index: {idx}, Fruit: {fruit}")
Output:
Here, itertools.count() generates a sequence of numbers starting from 0, and zip(itertools.count(), list1) pairs each index with the corresponding element.
Conclusion
We can use loops to access and modify elements of various types such as dictionaries, lists, etc. By using enumerate(), range(), or other approaches, where we can easily access the index of elements while iterating, which makes your code more efficient and readable.