Python enumerate for loops

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.

    Источник

    Питонистический подход к циклам for: range() и enumerate()

    Автор заметки, перевод которой мы сегодня публикуем, хочет рассказать о некоторых особенностях использования циклов for в Python.

    Цикл for — это один из краеугольных камней программирования. С этими циклами будущие программисты знакомятся в самом начале учёбы и, после первого знакомства, пользуются ими постоянно.

    Если вы занялись разработкой на Python, имея опыт работы с другим популярным языком программирования, вроде PHP или JavaScript, то вам знакома методика применения переменной-счётчика, хранящей, например, индекс текущего элемента массива, обрабатываемого в цикле. Вот пример работы с циклом, написанный на JavaScript:

    let scores = [54,67,48,99,27]; for(const i=0; i < scores.length; i++) < console.log(i, scores[i]); >/* 0 54 1 67 2 48 3 99 4 27 */

    Работая с циклами for очень важно понимать то, что эти циклы не перебирают массивы. Они лишь дают программисту механизм для работы с переменной-счётчиком, которая используется для обращения к элементам обрабатываемых массивов.

    В предыдущем примере переменная i не имеет какого-то явного отношения к массиву scores . Она всего лишь хранит некое число, которое увеличивается на 1 в каждой итерации цикла, и которое, как оказывается, подходит для последовательного обращения к элементам массива по их индексам.

    Старый (неудачный) способ работы с массивами

    В Python нет традиционных циклов for , подобных тому, что показан выше. Правда, если вы похожи на меня, то первым вашим желанием при освоении Python станет поиск способа создания цикла, с которым вам привычно и удобно работать.

    В результате вы можете обнаружить функцию range() и написать на Python нечто подобное следующему:

    scores = [54,67,48,99,27] for i in range(len(scores)): print(i, scores[i]) """ 0 54 1 67 2 48 3 99 4 27 """

    Проблема этого цикла заключается в том, что он не очень хорошо соответствует идеологии Python. В нём мы не перебираем список, а, вместо этого, используем вспомогательную переменную i для обращения к элементам списка.

    На самом деле, даже в JavaScript существуют методы, позволяющие перебирать массивы, так сказать, без посредников. Речь идёт о циклах forEach и for of .

    Использование функции enumerate()

    Если вам нужно адекватным образом отслеживать «индекс элемента» в for -цикле Python, то для этого может подойти функция enumerate() , которая позволяет «пересчитать» итерируемый объект. Её можно использовать не только для обработки списков, но и для работы с другими типами данных — со строками, кортежами, словарями.

    Эта функция принимает два аргумента: итерируемый объект и необязательное начальное значение счётчика.

    Если начальное значение счётчика enumerate() не передаётся — оно, по умолчанию, устанавливается в 0 . Функция создаёт объект, генерирующий кортежи, состоящие из индекса элемента и самого этого элемента.

    scores = [54,67,48,99,27] for i, score in enumerate(scores): print(i, score)

    Такой код получился гораздо чище кода из предыдущего примера. Мы ушли от работы со списком индексов, мы перебираем сами значения, получая к ним прямой доступ в цикле for, и видим значения, с которыми работаем, в объявлении цикла.

    Вот одна приятная возможность, которая понравится тем, кому нужно выводить нумерованные списки так, чтобы номер первого элемента был бы не 0 , в соответствии с его индексом, а 1 . Обычно для того, чтобы это сделать, приходится менять выводимый номер элемента. Например — так: i + 1 . При использовании же функции enumerate() достаточно передать ей, в качестве второго аргумента, то число, с которого нужно начинать нумерацию. В нашем случае — 1 :

    scores = [54,67,48,99,27] for i, score in enumerate(scores, 1): print(i, score) """ 1 54 2 67 3 48 4 99 5 27 """

    Итоги

    Надеюсь, этот небольшой рассказ о циклах for в Python позволил вам узнать что-то новое об этом языке.

    Уважаемые читатели! Знаете ли вы ещё какие-нибудь способы применения функции enumerate() ? Кажутся ли вам циклы, построенные с использованием enumerate() , более читабельными, чем циклы, созданные с использованием range(len()) ?

    Источник

    Читайте также:  Javascript validate phone numbers
Оцените статью