Built with Tutify.io

    AIStudyLabs

    Python - Access Index in For Loop With Examples

    Python - Access Index in For Loop With Examples

    How to access an index in a Python for loop? By default Python for loop doesn't support accessing the index, the reason being for loop in Python is similar to foreach where you don't have access to the index while iterating sequence types (list, set, etc.).

    For example, if you have knowledge in C, C++, Java, or Javascript you know for loops are used with the counter to iterate arrays/lists, you use a counter variable and manually increment it for each iteration. This counter variable is used as an index to access items from sequence type within a for loop.

    But Python for loop simplified this not to use a counter/index variable and provides a way to loop through each element in an iterable object. However, there are a few ways to access an index in Python for loop.

    In this article, you will learn how to access the index in Python for loop with examples.

    1. Quick Examples of Accessing Index in Python For Loop

    If you are in a hurry, below are some quick examples of accessing the index from the for loop.

    
    # Below are examples of accessing index in for loop
    
    courses=['java','python','pandas','sparks']
    
    # Example 1: Using enumerate() to access both index & items
    for index , item in enumerate(courses):
        print(index,item)
    
    # Example 2: Start loop indexing with non zero value
    for index , item in enumerate(courses,start=1):
        print(index,item)
    
    # Example 3: range() to access both index & item
    for index in range(len(courses)):
        item = courses[index]
        print(index, item)
    
    # Example 4: Use list comprehension to access both index & item
    print([list((i, courses[i])) for i in range(len(courses))])
    
    # Example 5: Using Zip() to access index
    for x in zip(range(len(courses)), courses):
            print(x)
    

    If you want to learn more about each example from above, continue reading the article where I have explained it in detail with output.

    Table of contents

    1. Using the enumerate() function to access the index in a for loop.
    2. Using range() function.
    3. Using list comprehension.
    4. Using the zip() function.

    <a id="using-enumerate-to-access-index-in-python-for-loop"></a>

    2. Using enumerate() to Get Index and Value in Python For Loop

    Use the Python enumerate() function to access the index in a for loop. enumerate() method is an in-built method in Python, which is a good choice when you want to access both the items and the indices of a list. enumerate() method is the most efficient method for accessing the index in a for loop.

    2.1 Syntax of enumerate()

    Following is a syntax of the enumerate() function that I will be using throughout the article.

    
    # Syntax of enumerate()
    enumerate(iterable_object, start=0)
    
    
    # Using type() to get enumerate type
    courses = ["java","python","pandas"]
    courses_index = enumerate(courses)
    print(type(courses_index))
    
    # Output:
    # <class 'enumerate'>
    

    <a id="h-2-2-convert-enumerate-to-list"></a>

    2.2 Convert enumerate to List

    The enumerate() method combines indices to iterable objects and returns them as an enumerated object. This enumerated object can be easily converted to a list using a list(). This is the easiest way of accessing both items and their indices at once. You need to understand this as it will give you insight into how enumerate gives you an index.

    
    # Convert enumerate object to list object
    courses = ["java","python","pandas"]
    courses_index = enumerate(courses)
    print(list(courses_index))
    
    # Output:
    # [(0, 'java'), (1, 'python'), (2, 'pandas')]
    

    As you see, the names in the list are now inside a tuple and every name has its index.

    <a id="h-2-3-use-enumerate-to-access-both-index-and-value-in-a-for-loop"></a>

    2.3 Use enumerate() to Access Both Index and Value in a For Loop

    When you use enumerate() with for loop, it returns an index and item for each element in an enumerate. This method combines indices to iterable objects and returns them as an enumerated object.

    In the below example, enumerate(courses) returns pairs of index and value for each element in the list. The for loop then iterates over these pairs, and you can use the index variable to access the index of the current element.

    
    # Using enumerate() to access both index & item
    courses = ['java','python','pandas','sparks']
    print("Get both index & item of the list:")
    for index , item in enumerate(courses):
        print(f"Index: {index}, item: {item}")
    

    Yields below output.

    <a id="h-2-4-access-python-for-loop-index-start-at-1"></a>

    2.4 Access Python For Loop Index Start at 1

    If you want to start the index of a for loop at 1 instead of 0, you can specify the starting value when using the enumerate function.

    In the below example, the start=1 parameter is used in the enumerate function to start the index at 1. This way, the loop iterates over the elements in the list, and the index variable starts from 1 instead of 0.

    
    # Start loop indexing with non zero value
    courses=['java','python','pandas','sparks']
    print("Get the index of for loop start at 1:")
    for index, item in enumerate(courses, start = 1):
        print(f"Index: {index}, item: {item}")
    

    Yields below output.

    Similar to the enumerate() function, we have other ways to access the index in a for loop.

    <a id="using-range-function-for-loop-access-index-in-python"></a>

    3. Using range() to Access For Loop Index in Python

    Using therange() function you can get a sequence of values starting from zero. Hence, use this to access an index in a for loop. Use the len() function to get the number of elements from the list/set object.

    We have passed a sequence of numbers in the range from 0 to len(courses) with the index. Then, we use this index variable to access the items of the list in order from 0 to 3, where 3 is the end of the list.

    Note that for every iteration the index will be increased and returned with the corresponding item.

    
    # Using range() to access both index & item
    courses = ['java','python','pandas','sparks']
    for index in range(len(courses)):
        item = courses[index]
        print(index, item)
    

    Yields below output.

    
    # Output:
    0 java
    1 python
    2 pandas
    3 sparks
    

    According to the above example using a for loop, iterate over the length of courses. Here the iteration of len(courses) starts from 0 to 3 with the index. Using index variable to access the items of the list in order of 0 to 3, where 0 is the default index and 3 is the last item of the list. In every iteration of a loop, access the value of the list with the corresponding index using the variable item=course[index].

    <a id="using-list-comprehension"></a>

    4. Using List Comprehension

    List comprehension allows a lesser syntax for creating a new list based on an already existing list. Using list comprehension you can manipulate lists, more efficiently compared to functions and for loops.

    4.1 Syntax of the List Comprehension

    
    # Syntax of the list comprehension
    [expression for item in list]
    

    Let's take a simple example for better understanding.

    
    # Using list comprehension manipulate list
    list = [20,10,40,50]
    products = [x*2 for x in list]
    print(products)
    

    Yields below output

    
    # Output:
    [40, 20, 80, 100]
    

    According to the above example in the list comprehension, List represents iterable object x represents item and x*2 represents expression.

    4.2 Use a List Comprehension to Access Indices of Python For Loop

    You can use list comprehension to create a list of tuples, where each tuple contains an index and the corresponding item from the courses list. However, you can simplify it a bit by using enumerate. In this version, enumerate(courses) is used directly in the list comprehension to get pairs of index and items, making the code more concise.

    
    # Use list comprehension to access both index & item
    courses=['java','python','pandas','sparks']
    print([list((i, courses[i])) for i in range(len(courses))])
    

    Yields below output.

    
    # Output:
    [[0, 'java'], [1, 'python'], [2, 'pandas'], [3, 'sparks']]
    

    You got 4 lists as an output, containing the index and its corresponding item in courses.

    <a id="using-zip-function-for-loop-access-index-in-python"></a>

    5. Using Zip() Function to Access Index in a For Loop

    The zip() function allows one or more iterable objects (such as a list, tuple, set, or dictionary), this returns a zip object. This is an iterator of tuples where each tuple contains elements from each iterable. zip() function allows an iterable such as a list, tuple, set, or dictionary as an argument.

    
    # Using Zip() function
    courses = ["java","python","pandas"]
    for x in zip(range(len(courses)), courses):
            print(x)
    

    Yields below output

    
    # Output:
    (0, 'java')
    (1, 'python')
    (2, 'pandas')
    

    In the above example, I have passed a sequence of numbers in the range from 0 to len(courses) as the first parameter of the zip() function, and courses as the second parameter. The zip() connects each index with its corresponding value, and it returns the Zip object. This is an iterator of tuples where each tuple contains elements from each iterable.

    <a id="h-frequently-asked-questions-on-access-index-in-python-for-loop"></a>

    Frequently Asked Questions on Access Index in Python For Loop

    You can use the enumerate() function in a for loop to access both the elements and their corresponding indices. For example, the enumerate() function is used in the for loop to iterate over both the indices and values of the courses. The index variable holds the index of the current element, and the value variable holds the value of the element.

    You can start the index at a different value by specifying the start parameter in the enumerate() function. For example, the start=1 parameter is used in the enumerate() function. As a result, the index of the first element will be 1, and subsequent indices will follow accordingly.

    You can use list comprehension with enumerate() to create a list of tuples containing indices and corresponding elements. For example, the enumerate() function is used within the list comprehension to iterate over the elements of the courses list, and for each element, a tuple containing the index and the element is created. The resulting list, result.

    You can iterate over a string and access both the character and its index using a combination of enumerate() and a loop, just like you would with a list.

    When iterating over a range of numbers in a for loop in Python, you can use the enumerate function to access both the index and the value at that index.

    <a id="h-conclusion"></a>

    Conclusion

    In this article, you have learned to access iterable objects with the index in the for loop by using range(), enumerate() and zip(). You have also learned the basic idea of list comprehension, using this how we can access the index with corresponding items.

    Happy Learning !!

    Related Articles