Python index in for cycle

Accessing Python for loop index [4 Ways]

In this Python tutorial, we will discuss Python for loop index. Here we will also cover the below examples:

A for loop in Python is used to iterate over a sequence (such as a list, tuple, or string) and execute a block of code for each item in the sequence. The loop variable, also known as the index, is used to reference the current item in the sequence.

There are 4 ways to check the index in a for loop in Python:

  1. Using the enumerate() function
  2. Using the range() function
  3. Using the zip() function
  4. Using the map() function

Method-1: Using the enumerate() function

The “enumerate” function is one of the most convenient and readable ways to check the index in for loop when iterating over a sequence in Python.

# This line creates a new list named "new_lis" with the values [2, 8, 1, 4, 6] new_lis = [2, 8, 1, 4, 6] # This line starts a for loop using the enumerate function to iterate over the "new_lis" list. # The loop variable "x" is used to reference the current index, and "new_val" is used to reference the current value. for x, new_val in enumerate(new_lis): # This line prints the current index and value of the item in the list, separated by a comma. print (x, ",",new_val) 

In the above example, the enumerate function is used to iterate over the new_lis list.

  • Where the variable x will be the current element’s index and new_val will be the value of that element.
  • The print statement will print the index and the value of that element separated by a comma, for each element in the list.
Читайте также:  Css как поменять прицел

Python for loop index

So, in this section, we understood how to use the enumerate() for accessing the Python For Loop Index.

Method-2: Using the range() function

The “range” function can be used to generate a list of indices that correspond to the items in a sequence. This allows you to reference the current index using the loop variable.

# This line creates a new list named "my_lis" with the values [6, 1, 9, 2] my_lis = [6, 1, 9, 2] # This line starts a for loop using the range function to iterate over the indices of the "my_lis" list. # The loop variable "new_indic" is used to reference the current index. for new_indic in range(len(my_lis)): # This line prints the current index and the value of the element at that index in the list print(new_indic, my_lis[new_indic]) 

In the above example, the range function is used to generate a list of indices that correspond to the items in the “my_lis” list.

  • The for loop iterates over that range of indices, and for each iteration, the current index is stored in the variable new_indic.
  • The element’s value at that index is printed by accessing it from the “my_lis” list using the new_indic variable.

Python for loop index range function

So, in this section, we understood how to use the range() for accessing the Python For Loop Index.

Method-3: Using the zip() function

The “zip” function can be used to iterate over multiple sequences in parallel, allowing you to reference the corresponding items at each index.

# This line creates a new list named "new_str" with the values ['e', 'f', 'i'] new_str = ['e', 'f', 'i'] # This line starts a for loop using the zip function to iterate over the "new_str" list and a range of indices. # The loop variable "m" is used to reference the current tuple of index and value. for m in zip(range(len(new_str)), new_str): # This line prints the current tuple of index and value of the item in the list print(m) 

In the above example, the range function is used to generate a list of indices that correspond to the items in the “new_str” list.

  • The zip function is used to combine the indices from the range function and the items from the “new_str” list, and iterate over them in parallel.
  • For each iteration, the current tuple of index and value is stored in the variable m and printed.

Python for loop index zip function

So, in this section, we understood how to use the zip() for accessing the Python For Loop Index.

Method-4: Using the map() function

The “map” function takes a function and an iterable as arguments and applies the function to each item in the iterable, returning an iterator.

The function passed to “map” can take an additional parameter to represent the index of the current item.

# This line creates a new list named "new_str2" with the values ['Germany', 'England', 'France'] new_str2 = ['Germany', 'England', 'France'] # This line uses the map function to apply a lambda function to a range of indices and items of the "new_str2" list. # The lambda function returns a tuple of the form (index, value) for each item in the "new_str2" list. new_out = map(lambda o: (o, new_str2[o]), range(len(new_str2))) # This line converts the map object to a list and prints it print(list(new_out)) 

In the above example, the code creates a list named “new_str2” with the values [‘Germany’, ‘England’, ‘France’].

  • The map() function is used to apply a lambda function to a range of indices and items of the “new_str2” list.
  • The lambda function takes the index of the current item as an argument and returns a tuple of the form (index, value) for each item in the “new_str2” list.
  • The map() function returns an iterator that contains the tuples of index and value for each item in the “new_str2” list. The result of the map function is then converted to a list and printed.

Python for loop index map function

So, in this section, we understood how to use the map() for accessing the Python For Loop Index.

You may also like to read the following Python tutorials.

In this Python tutorial, we will discuss Python for loop index to know how to access the index using the different methods. Here is the set of methods that we covered:

  • Using the enumerate() function
  • Using the range() function
  • Using the zip() function
  • Using the map() function

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Как получить доступ к индексу в цикле Python

Python — это язык программирования очень высокого уровня, и он имеет тенденцию отклоняться от всего, отдаленно напоминающего внутреннюю структуру данных. Из-за этого нам обычно не нужны индексы списка для доступа к его элементам, однако иногда они нам очень нужны.

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

Как получить индекс?

Самый простой и самый популярный метод доступа к индексу элементов в цикле for — это просмотреть длину списка, увеличивая index . При каждом увеличении мы получаем доступ к списку index :

my_list = [3, 5, 4, 2, 2, 5, 5] print("Indices and values in my_list:") for index in range(len(my_list)): print(index, my_list[index], end = "\n") 

Здесь мы не перебираем список, как обычно. Мы выполняем итерацию 0..len(my_list) с помощью index . Затем мы используем эту переменную index для доступа к элементам списка в порядке 0..n , где n — конец списка.

Этот код выдаст результат:

Indices and values in my_list: 0 3 1 5 2 4 3 2 4 2 5 5 6 5

Использование enumerate()

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

Этот метод добавляет счетчик к итерируемому объекту и возвращает их вместе как перечислимый объект. Этот объект перечисления можно легко преобразовать в список с помощью конструктора list() . Это наиболее распространенный способ одновременного доступа к обоим элементам и их индексам.

Теперь давайте посмотрим на код, который иллюстрирует использование этого метода:

my_list = [3, 5, 4, 2, 2, 5, 5] print("Indices and values in my_list:") for index, value in enumerate(my_list): print(list((index, value))) 

Этот код выдаст результат:

Indices and values in my_list: [0, 3] [1, 5] [2, 4] [3, 2] [4, 2] [5, 5] [6, 5]

В этом примере мы перечислили каждое значение в списке с его соответствующим индексом, создав объект enumerate. Затем мы преобразовали этот объект перечисления в список с помощью конструктора list() и распечатали каждый список в стандартный вывод.

Кроме того, вы можете установить аргумент start для изменения индексации. В настоящее время он имеет значение 0. Давайте вместо этого изменим его, чтобы начать с 1 :

my_list = [3, 5, 4, 2, 2, 5, 5] print("Indices and values in my_list:") for index, value in enumerate(my_list, start=1): print(list((index, value))) 
Indices and values in my_list: [1, 3] [2, 5] [3, 4] [4, 2] [5, 2] [6, 5] [7, 5] 

Использование списков

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

Каждое представление списка в Python содержит эти три элемента:

  1. iterable — коллекция, элементы которой мы можем проверять по одному
  2. member — значение или объект в списке (который является повторяемым)
  3. expression — может быть любым допустимым выражением, возвращающим значение (член, итерация, вызов функции . )

Давайте посмотрим на следующий пример:

my_list = [1, 2, 3, 4, 5] my_list_squared = [m*m for m in my_list] print(my_list_squared) 

Этот код выдаст результат:

В этом понимании список my_list представляет итерируемый объект, m представляет член и m*m представляет выражение.

Теперь, когда мы рассмотрели, что такое понимание списка, мы можем использовать его для перебора списка и доступа к его индексам и соответствующим значениям. Давайте посмотрим на этот пример:

my_list = [3, 5, 4, 2, 2, 5, 5] print("Indices and values in my_list:") print([list((i, my_list[i])) for i in range(len(my_list))]) 

Этот код выдаст результат:

Indices and values in my_list: [[0, 3], [1, 5], [2, 4], [3, 2], [4, 2], [5, 5], [6, 5]] 

В этом примере мы использовали конструктор list() . Этот конструктор не принимает аргументов или имеет один аргумент — итерацию. Сюда входит любой объект, который может быть последовательностью (строка, кортежи) или коллекцией (набор, словарь).

Если параметры не переданы, он возвращает пустой список, а если итерируемый объект передается в качестве параметра, он создает список, состоящий из его элементов.

Мы построили список из двух элементов, которые имеют формат [elementIndex, elementValue] . Эти двухэлементные списки были созданы путем передачи пар конструктора list() , который затем выдал эквивалентный список.

Это создаст 7 отдельных списков, содержащих индекс и соответствующее ему значение, которые будут напечатаны.

Использование zip()

Функция zip() принимает два или более параметров, которые все должны быть итерируемые.

Он возвращает zip-объект — итератор кортежей, в котором первый элемент в каждом переданном итераторе объединяется в пары, второй элемент в каждом переданном итераторе объединяется в пары, и аналогично для остальных из них:

list_a = [1, 2, 3] list_b = ['A', 'B', 'C'] # Zip will make touples from elements with the same # index (position in the list). Meaning that 1 from the # first list will be paired with 'A', 2 will be paired # with 'B' and so on. for elem1,elem2 in zip(list_a,list_b): print((elem1,elem2)) 

Запустив приведенный выше фрагмент кода, мы получим:

Длина итератора, возвращаемого этой функцией, равна длине наименьшего из ее параметров.

Теперь, когда мы объяснили, как работает эта функция, давайте воспользуемся ею для решения нашей задачи:

my_list = [3, 5, 4, 2, 2, 5, 5] print ("Indices and values in my_list:") for index, value in zip(range(len(my_list)), my_list): print((index, value)) 

Этот код выдаст результат:

Indices and values in my_list: (0, 3) (1, 5) (2, 4) (3, 2) (4, 2) (5, 5) (6, 5) 

В этом примере мы передали последовательность чисел в диапазоне от 0 до len(my_list) в качестве первого параметра функции zip() и my_list ее второго параметра. Функция объединила каждый индекс с соответствующим значением, и мы распечатали их как кортежи с помощью цикла for .

Если бы мы хотели преобразовать эти кортежи в список, мы бы использовали конструктор list() , и наша функция print выглядела бы так:

Источник

Оцените статью