# Accessing The Index Of Iterables In Python

Rate this post

Summary: To access the index of iterables like lists in Python, use one of the following methods:

Introduction

An index can be considered as the position of an element in an ordered datatype (like a list or tuple). A string can be considered as a list of characters with each character having an index.

• Indexing starts from zero to the length-1.
• Python also supports negative indexing.

Let’s visualize indexing with the help of a diagram.

From the above example, it is quite clear that:

• The length of the string is 23 while the indexing starts at 0 and ends at 22.
• Negative Indexing starts from the end of the string with -1 and ends at the beginning of the string (-23).

Now that we have an idea about indexes, let us dive into our mission-critical question:

Problem: Give a list; how to access the index of each element of the list using a loop or any other method?

Example 1: Consider the program given below which contains a list of numbers. We want to extract the each number along with it’s index as shown below:

```items = [100, 200, 300, 400, 500]
for i in items:
print('item #{} = {}'.format(???, i))```

Desired Output

```item #0 = 100
item #1 = 200
item #2 = 300
item #3 = 400
item #4 = 500```

Now let us have a look at the different ways of doing this:

## Method 1 : Using enumerate() function

The most effective way of finding the index of elements in a list is to use an inbuilt Python function known as `enumerate()`. This method accepts an iterable (like a list, tuple) adds a counter to it, and then returns it as an object.

`enumerate(iterable, start)` : Syntax for the `enumerate()` method.

Note: Indexing starts at 0 in Python, so you must define a start number in case you want to use a different number as the starting index.

Let us have a look at the following program to understand how we can use this method to find the indexes of the elements in the list :

```items = [100, 200, 300, 400, 500]
for index, item in enumerate(items, start=1):
print('item #{0} = {1}'.format(index, item))```

Output:

```item #1 = 100
item #2 = 200
item #3 = 300
item #4 = 400
item #5 = 500```

## Method 2: Using A Counter Variable And A For Loop

You can create a for loop using a variable to store the index and access the elements of the list using this variable. Let us have a look at the following program to understand how this works:

```items = [100, 200, 300, 400, 500]
for i in range(len(items)):
print(f'item #{i + 1} = {items[i]}')```

Output:

```item #1 = 100
item #2 = 200
item #3 = 300
item #4 = 400
item #5 = 500```

## Method 3: Using A While Loop And A Counter Variable

Just like the for loop, we can also use a while loop to create a counter variable to hold the indexes of the elements and then access the elements of the list using this variable. Let us have a look at the following program to understand how this works:

```items = [100, 200, 300, 400, 500]
i = 0
while i <= len(items):
print(f'item #{i + 1} = {items[i]}')
i += 1```

Output:

```item #1 = 100
item #2 = 200
item #3 = 300
item #4 = 400
item #5 = 500```

## Method 4: Using a List Comprehension

Let us have a look at the Python one-liner to solve our problem using a list comprehension:

```items = [100, 200, 300, 400, 500]
[print(f"item #{index + 1} = {items[index]}") for index, item in enumerate(items)]```

Output:

```item #1 = 100
item #2 = 200
item #3 = 300
item #4 = 400
item #5 = 500```

## Method 5: Using Itertools Module

We can use the `count()` and `zip()` functions of the `itertools `module to find the index of the given item.

1. `count()` is an inbuilt function of the `itertools `module that is used to create an iterator and produces consecutive integers based on the given start and step attribute values.
2. `zip()` is another inbuilt function of the `itertools `module that accepts an iterable as an argument which can be a list, tuple, file, dictionary, etc. It combines the elements of several iterators and stores them into tuples.

Now let us see how we can apply the above concept in our solution:

```from itertools import count

items = [100, 200, 300, 400, 500]
for i in zip(count(start=1, step=1), items):
print(i)```

Output

(1, 100)
(2, 200)
(3, 300)
(4, 400)
(5, 500)

## Method 6: Using the NumPy Library

Another approach to find indices is to use the `numpy` library. You might be wondering why should you use an external library to find an index of an element in a list. Does that even make any sense? Yes, it does. You will not find this method effective in case of simple scenarios, however, in situations where you need to perform complex operations using indexes, `numpy `is the most efficient solution in such scenarios. NumPy is almost 50 times faster than traditional lists and that’s why it needs an honorable mention in the list of our suggested solutions.

To understand the power of `NumPy `let us consider a different example where you have to find the index of a given number in a collection. Please follow the code given below:

```import numpy as np

items = [500, 200, 500, 400, 500]
value = 500
# numpy.where() function returns the indices of elements in an input array where the given condition is satisfied.
index = np.where(np.array(items) == value)
print(f'item {value} is located at INDEX: {index}')```

Output:

`item 500 is located at INDEX: [0 2 4]`

One might argue that the above solution could be reached via other methods too. However, the effectiveness and ease with which NumPy resolves our issue makes it a good option.

## Conclusion

Thus, in this article the solutions described above included the following methods:

1. Using enumerate() function.
2. Using a counter variable with For Loop/While Loop.
3. Using a list comprehension.
4. Using `itertools `module.
5. Using the `NumPy `library.

I hope after reading this article you can find indices of items in lists or arrays without any hassle. Please subscribe and stay tuned for more interesting articles.

## Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now! 