Python foreach list with index

Python For Loop with Index: Access the Index in a For Loop

To access the index in a for loop in Python, use the enumerate() function.

names = ["Alice", "Bob", "Charlie"] for position, name in enumerate(names): print(f": ")

This is a quick answer to your question.

However, if you are unfamiliar with the syntax, or want to figure out alternative ways to access the index in a for loop, please stick around.

In this guide you learn how to:

  • Use the enumerate() function to get a for loop index.
  • How to start loop index at 1 or some other value than 0.
  • Alternative ways to perform a for loop with index, such as:
    • Update an index variable
    • List comprehension
    • The zip() function
    • The range() function

    The enumerate() Function in Python

    The most elegant way to access the index of for loop in Python is by using the built-in enumerate() function.

    Before seeing a bunch of examples, let’s take a look at how the enumerate() function works.

    How Does the enumerate() Function Work

    The enumerate() function can be called on any iterable in Python.

    It then couples each element in the iterable with an index and returns the result as an enumerate object.

    To visualize the enumerate object, you can convert it to a list using the list() function.

    names = ["Alice", "Bob", "Charlie"] names_idx = enumerate(names) print(list(names_idx))

    As you can see, the names in the list are now inside a tuple and for each name, there is a related index.

    Here is an illustration of the enumeration process:

    Python enumerate function couples elements with index

    When you call enumerate() the indexing starts at 0 by default.

    However, you can change this by specifying an optional start parameter to the enumerate() function call.

    For instance, let’s make indexing start at 1:

    names = ["Alice", "Bob", "Charlie"] names_idx = enumerate(names, start=1) print(list(names_idx))

    Now that you understand how the enumerate() function works, let’s use it to access the index in a for loop.

    How to Get the Index in For Loop

    To get the index in a for loop:

    names = ["Alice", "Bob", "Charlie"] names_idx = enumerate(names) for index, name in names_idx: print(f": ")

    If you are a beginner and have a hard time understanding the index, name part in the loop, please check the tuple unpacking article.

    By the way, you do not need to separately store the enumerated iterable into a separate variable. Instead, you can call the enumerate() function directly when starting the for loop.

    This saves you a line of code.

    names = ["Alice", "Bob", "Charlie"] for index, name in enumerate(names): print(f": ")

    Next, let’s take a look at how to change the index at which the enumeration starts.

    How to Start Indexing at a Custom Value

    In the previous example, the indexing starts at 0.

    However, it is quite common you want the indexing to start from somewhere else than 0.

    Luckily, the enumerate() function makes it possible to specify a non-zero starting index.

    To for loop with index other than 0:

    For example, let’s make indexing start at 1:

    names = ["Alice", "Bob", "Charlie"] for index, name in enumerate(names, start=1): print(f": ")

    Enumerate Works with All Iterables

    So far you have only seen how to access for loop index when dealing with lists in Python.

    However, you can call the enumerate() function on any iterable type in Python, such as a tuple or string.

    By the way, if you are unfamiliar with iterables, please check this complete guide.

    For example, let’s get the indices of each letter in a string:

    word = "Hello" for pos, letter in enumerate(word): print(f": ")

    Now you understand how to use the enumerate() function to get the index of a for loop in Python.

    This is such an elegant solution to the problem. I recommend you stick with it.

    However, for the sake of completeness, I am going to show alternative ways to index for loops.

    Alternative Ways to For Loops with Index

    Here is a list of alternative ways to access the for loop index in Python.

    Separate Index Variable

    The most basic way to get the index of a for loop is by keeping track of an index variable.

    This is commonly taught in beginner-level programming courses. Also, some programming languages do not even have a function like enumerate() you could use.

    For instance, let’s print the names and their position in a list:

    names = ["Alice", "Bob", "Charlie"] index = 0 for name in names: print(f": ") index += 1

    The downside to this approach is the fact you need to remember to update the additional index variable. This introduces unnecessary code and makes the code susceptible to bugs and unintended behavior.

    Because there is a separate function enumerate() dedicate to tackling this problem, it is better to use it instead.

    The zip() Function

    Given an iterable of elements and a separate list of indices, you can couple these two together using the zip() function.

    names = ["Alice", "Bob", "Charlie"] indexes = [0, 1, 2] for index, name in zip(indexes, names): print(f": ")

    However, this is usually quite impractical due to the fact that you should specify a separate sequence for the indices.

    If you do not have a separate index list, you could of course create one using the range() function and then zip it with the list:

    names = ["Alice", "Bob", "Charlie"] indexes = range(len(names)) for index, name in zip(indexes, names): print(f": ")

    Anyway, doing this is quite useless because the built-in enumerate() function does exactly this with less code and more understandability.

    The range() Function

    In Python, you can use the range() function to create a range of numbers from a starting point to an end.

    It is easy to loop over a range in Python.

    Given the length of an iterable, you can generate a range of indexes using the range() function. Then you can use these indices to access the elements of the iterable in a for loop.

    names = ["Alice", "Bob", "Charlie"] for i in range(len(names)): print(f": ")

    List Comprehension

    Last but not least, you may have heard about list comprehensions in Python.

    A list comprehension offers a one-liner shorthand for using a for loop. Using list comprehensions is never mandatory. Sometimes it can be convenient to convert a basic for loop into a short one-liner list comprehension.

    Anyway, you can use list comprehension when you want to access the index of a for loop.

    For instance, let’s combine a list comprehension and the enumerate() function to create a short for loop with index:

    names = ["Alice", "Bob", "Charlie"] [print(f": ") for index, name in enumerate(names)]

    Even though this expression saves you a line of code, one could argue it looks cleaner when used as a regular for loop.

    Be cautious not to sacrifice code quality with comprehensions!

    Conclusion

    Today you learned how to access the index in a for loop in Python.

    To recap, there is a built-in enumerate() function that can be called on any iterable. It couples the elements with an index that you can use when looping through it.

    In addition to using the enumerate() function, there is a bunch of (usually worse) options to looping with index:

    • Update an index variable.
    • The zip() function.
    • The range() function.
    • List comprehension.

    Источник

    Читайте также:  Python использование русского языка
Оцените статью