Looping through a list with enumerate #
Sometimes, when looping over a sequence or collection, such as strings, lists, or tuples in Python, you may need to access both the elements themselves and their corresponding indexes. In such cases, you can use the enumerate() function to obtain the index and value of each element during iteration.
Here's what happens when you call enumerate() with a list as the argument.
names = ["John", "Jane", "Michael"]
print(list(enumerate(names)))
Output
[(0, 'John'), (1, 'Jane'), (2, 'Michael')]
In this example, the enumerate() function generates a sequence of index-value pairs for the list names.
We can use data unpacking to loop through the list, like so:
selected_names = []
for index, name in enumerate(names):
if index % 2 == 0:
selected_names.append(name)
print(selected_names) # ['John', 'Michael']
In the example above, the goal is to select and store the names at even positions from the original list. The if statement with the modulo operator % helps filter out the names based on their index. The resulting names are then added to the selected_names list using the append() method.
Exercise #
Use the function enumerate() to loop through the given list names and append all the values except the first element to the output list.
Tests #
- Use the function
enumerate() outputshould be['Cassandra Sullivan', 'Brooke Stevens', 'Amanda Smith', 'Mary Smith']
Getting Started with Python
Data Types
Python Functions
Statements in Python
Basic Debugging in Python
Basic Algorithm
Object-Oriented Programming
Error Handling
Intermediate Algorithm
Python Modules