6 Ways to Use Python's enumerate for Better Loop Control - NBD Lite #28
Leverage in-built Python library to improve your works.
One of the most tedious tasks of data scientists is to loop through the data.
It’s a task that can be daunting yet necessary.
Luckily, there is the Python’s built-in enumerate
that could help the looping process.
The enumerate
function is essential if we want through iterable objects while keeping track of the index.
The function would be cleaner and more readable without additional dependencies.
Below are six practical ways enumerate
to write more efficient loops in the data science workflow.
Let’s explore them together! Here is the summary that we will discuss together.
1. Index-Based Data Processing
There are situations during our data processing where we would need both the index and value from the list.
Without using enumerate
, we would need a manual counter that makes the code less efficient. That’s why we could rely on enumerate
looping through the index and values.
Below is a code example of how to do that.
data = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(data):
print(f"Index {i}: {fruit}")
By using enumerate
, the loop returns both the index (i
) and the value (fruit
) for each item in the list.
This is useful when the element's position is important.
2. Parallel Loop Control
Many times, we have been working with multiple lists containing different data points.
In this case, it would be essential to align the position of the elements based on the index.
To do that, we can use enumerate
to simplify the process of accessing index elements from each list in the same loop.
For example, we can do that in the code below.
names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]
for i, name in enumerate(names):
print(f"{name} scored {scores[i]}")
The example shows how enumerate
ensures that each name is printed along with its corresponding score.
3. Tracking Changes in Mutable List
Working with the data means that there are times when we need to make modifications.
It’s especially common that we need to make some changes during the iteration process.
So, it’s important to know the index position when we want to modify the data.
Using enumerate
, it gives us direct access to the index and makes the task easier.
data = [1, 2, 3, 4, 5]
for i, val in enumerate(data):
if val % 2 == 0:
data[i] = val * 2
print(data)
In-place modification of lists is often necessary in data cleaning or transformation workflows.
With enumerate
, we can directly update the value at a specific index and avoid creating a new list.
This is especially helpful when working with large datasets with problematic memory efficiency.
4. Skipping Items by Index
Sometimes, we only want to process specific elements based on their index.
In this case, we can use enumerate
it to efficiently skip elements we don’t need.
data = ['a', 'b', 'c', 'd', 'e']
for i, value in enumerate(data):
if i % 2 == 0:
print(value)
Using the index from enumerate
, it would allow us to selectively process elements.
It would be useful in data processing when we have done sampling or feature selection in our dataset.
5. Creating Dictionaries
We can transform the list or data we have into dictionary forms, where each item is mapped to its index.
The enumerate
function helps the process using dictionary comprehension.
data = ['one', 'two', 'three']
data_dict = {i: value for i, value in enumerate(data)}
print(data_dict)
Transforming lists into dictionaries makes data lookups more efficient.
That’s why, the combination of enumerate
and dictionary comprehension would ensure a better solution for quick data retrieval.
6. Breaking a Loop Midway
We can use enumerate
function when we want to stop our looping process with certain conditions.
The conditions based on both the index and value would allow enumerate
function to manage the logic more easily.
data = ['start', 'process', 'end', 'skip', 'finish']
for i, value in enumerate(data):
if value == 'end':
print(f"Stopping at index {i}: {value}")
break
The code above shows how enumerate
simplifies the logic of breaking a loop based on multiple conditions—both index and value.
It can be applicable in data analysis where we want to stop the process when we encounter certain values.
It’s also useful for debugging and logging when we test our code.
That’s all you need to know why enumerate
function could improve our looping process.
Are there any more things you would love to discuss? Let’s talk about it together!
👇👇👇