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.

Quick Examples of Accessing Index in Python for Loop

Following are some of the 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.

1. 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.

1.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)
  • The enumerate() method can be used for any iterable objects such as list, or range.
  • Using enumerate() method you can access an index of iterable objects.
  • enumerate() method has two parameters: iterable objects( such as lists, and tuple) and start parameters.
  • enumerate() method starts with 0(by default).
  • It returns enumerated objects.

# Using type() to get enumerate type
courses = ["java","python","pandas"]
courses_index = enumerate(courses)
print(type(courses_index))

# Output:
# <class 'enumerate'>

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.

1.2 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.


# 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(index, item)

Yields below output.

python for loop index

1.3 Access Python For Loop Index Start at 1

If you want to start the index of the for loop with a non-zero number you can set the second argument(start) of the enumerate() function with a specified starting number.


# 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(index, item)

Yields below output.

python for loop index

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

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

Using the range() 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].

3. 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.

3.1 Syntax of the List Comprehension


# Syntax of the list comprehension
[expression for item in list]
  • List is a collection of elements
  • Item is an element present in the sequence that is iterable
  • expression is a combination of operators and operands that is interpreted to produce some other value.

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.

3.2 Use a List Comprehension to Access Indices of Python ForLoop.


# 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.

4. Using Zip() function to Access Index in a For Loop Python

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()
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 this 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.

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

Vijetha

With 5 of experience in technical writing, I have had the privilege to work with a diverse range of technologies like Python, Pandas, NumPy and R. During this time, I have consistently demonstrated my ability to grasp intricate technical details and transform them into comprehensible materials.
You are currently viewing Python – Access Index in For Loop With Examples