enumerate() Function šÆWelcome to our comprehensive guide on the enumerate() function in Python! This handy tool is a great help for iterating through lists, tuples, and other iterables while keeping track of the current index. Let's dive in! š
enumerate() function?The enumerate() function is a built-in function in Python that allows you to loop through an iterable (like a list or a tuple) and return a tuple for each iteration. The tuple consists of two elements: the current element and its index in the iterable.
# Here's a simple example
my_list = ['apple', 'banana', 'cherry']
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")Output:
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: cherry
š” Pro Tip: The enumerate() function can be particularly useful when you need to manipulate the elements of a list based on their position.
enumerate() šThe enumerate() function can also be used with a custom start index and with a step value. Here's an example:
my_list = [1, 2, 3, 4, 5]
for index, value in enumerate(my_list, start=1):
print(f"Index: {index}, Value: {value}")Output:
Index: 1, Value: 1
Index: 2, Value: 2
Index: 3, Value: 3
Index: 4, Value: 4
Index: 5, Value: 5
In the example above, we've set the start parameter to 1, so the indexing starts from 1 instead of 0. You can also use a step value to skip certain elements while iterating:
my_list = [0, 1, 2, 3, 4, 5]
for index, value in enumerate(my_list, start=0, step=2):
print(f"Index: {index}, Value: {value}")Output:
Index: 0, Value: 0
Index: 2, Value: 2
Index: 4, Value: 4
In this example, we've used a step parameter of 2, so the function skips every other element while iterating.
What does the `enumerate()` function do in Python?