Skip to content

Python – Access Index in For Loop With Examples Vijetha Spark By {Examples}

  • by

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

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 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 to Access Index in Python for Loop

Following are some of the quick examples of how to access the index from 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 wanted to learn more about each example from above, continue reading the article where I have explained it in detail with output.

Table of contents

Using the enumerate() function to access the index in a for loop.

Using range() function.

Using list comprehension.

Using zip() function.

1. Using enumerate() to Access Index in Python for Loop

Use the python enumerate() function to access the index in 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 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, range.

Using enumerate() method you can access an index of iterable objects.

enumerate() method has two parameters: iterable objects( such as list,tuple) and start parameter.

enumerate() method starts with 0(by default).

It returns enumerate 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 index in a for loop

When you use enumerate() with for loop, it returns an index and item for each element in a 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.

1.3 Start loop indexing with non-zero value

You can change the start parameter to change the indexing. By default, it is 0. Let’s start loop indexing with a non-zero value by using start=1 param. This starts indexing from 1.

# Start loop indexing with non zero value
courses=[‘java’,’python’,’pandas’,’sparks’]
for index , item in enumerate(courses,start=1):
print(index,item)

Yields below output.

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

2. Using range() function & For Loop Access 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, we can access the list with the corresponding index.

# 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 if you want to create 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 a elements present in the sequence which is iterable

expression is a combination of operators and operands that is interpreted to produce some other value.

Lets 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 corresponding items.

# 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 & For Loop Access Index in Python

The zip() function allows one or more iterable object (such as list, tuple, set, 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 for loop by using range(), enumerate() and zip(). You have also learned the basic idea of list comprehensions, using this how to access index with corresponding items.

Happy Learning !!

Related Articles

For Loop with If Statement in Python

For Loop Break Statement in Python

For Loop Iterate Over an Array in Python

For Loop Continue And Break in Python

How to Perform Decrement for Loop in Python

How to Increment for Loop in Python

For Loop Enumerate in Python

Get Counter Values in a for Loop in Python?

How to Start Python For Loop at 1

Skip Iterations in a Python For Loop
 How to access an index in Python for loop? By default Python for loop doesn’t support accessing index, the reason being for loop in Python is similar to foreach where you don’t have access to index while iterating sequence types (list, set e.t.c). For example, if you have knowledge in C, C++, Java, or Javascript  Read More Python, Python Tutorial, Python For Loop Examples 

Leave a Reply

Your email address will not be published. Required fields are marked *