Enumerate что делает python

Python enumerate() – What is the Enumerate Function in Python?

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Python enumerate() – What is the Enumerate Function in Python?

The enumerate() function in Python takes in a data collection as a parameter and returns an enumerate object.

The enumerate object is returned in a key-value pair format. The key is the corresponding index of each item and the value is the items.

In this article, we’ll see some examples of how to use the enumerate() function in Python.

We’ll talk about the syntax and parameters, how to use enumerate() , and how to loop through an enumerate object.

What Is the Syntax of the enumerate() Function in Python?

Here is the syntax of the enumerate() function and its parameters:

The enumerate() function takes in two parameters: iterable and start .

  • iterable is the data collection passed in to be returned as an enumerate object.
  • start is the starting index for the enumerate object. The default value is 0 so if you omit this parameter, 0 will be used as the first index.

How to Use the enumerate() Function in Python

In this section, we’ll look at some examples to help us understand the syntax and parameters shown in the last section.

Note that we have to specify the type of data format (like lists, sets, and so on) the enumerate object will be stored in when returned. You’ll understand this better in the examples.

enumerate() Function in Python Example #1

names = ["John", "Jane", "Doe"] enumNames = enumerate(names) print(list(enumNames)) # [(0, 'John'), (1, 'Jane'), (2, 'Doe')]

In the example above, we created a list called names .

We then converted the names variable into an enumerate object: enumerate(names) , and stored it in a variable called enumNames .

We wanted the enumerate object to be stored in a list when returned, so we did this: list(enumNames) .

When printed to the console, this is what the result looked like: [(0, ‘John’), (1, ‘Jane’), (2, ‘Doe’)]

As you can see in the result, they are in key-value pairs. The first index is 0 which is attached to the first item in the names list, the second is 1 and is attached to the second item in the names list, and so on.

In our example, we only used the first parameter.

In the next example, we’ll make use of both parameters so you can understand how the second parameter work.

enumerate() Function in Python Example #2

names = ["John", "Jane", "Doe"] enumNames = enumerate(names, 10) print(list(enumNames)) # [(10, 'John'), (11, 'Jane'), (12, 'Doe')]

In the example above, we’ve added a second parameter to the enumerate() function: enumerate(names, 10) .

The second parameter is 10. This will signify the starting index for the keys (indexes) in the enumerate object.

Here is our result: [(10, ‘John’), (11, ‘Jane’), (12, ‘Doe’)]

From the result, we can see that the first index is 10, the second 11, and so on.

How to Loop Through an Enumerate Object in Python

Here’s a simple example that shows how we can loop through an enumerate object in Python:

names = ["John", "Jane", "Doe"] enumNames = enumerate(names) for item in enumNames: print(item) # (0, 'John') # (1, 'Jane') # (2, 'Doe') 

Using a for loop, we iterated through the enumerate object: for item in enumNames:

When printed out, we got the items in the object listed out in their corresponding key-value pair order.

We can also make use of the second parameter like we did in the last section to change the starting value of the keys.

Summary

In this article, we talked about the enumerate() function in Python.

We started by taking a look at the function’s syntax and parameters.

We then saw some examples which helped us understand how to use the enumerate() function and its parameters.

Lastly, we saw how to loop through enumerate objects in Python using the for loop.

Источник

enumerate¶

sequence Required. Must be a sequence, an iterator, or some other object which supports iteration. start Optional. Index at which enumeration starts.

Return Value¶

Time Complexity¶

Remarks¶

The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence.

Example 1¶

>>> for i in enumerate((1, 2, 3)): . print i . (0, 1) (1, 2) (2, 3) 

Example 2¶

>>> e = enumerate([1, 2]) >>> e.next() (0, 1) >>> e.next() (1, 2) >>> e.next() Traceback (most recent call last): File "", line 1, in StopIteration 

Example 3¶

>>> e = enumerate([1, 2, 3], 1) >>> e = enumerate([1, 2, 3], start=1) >>> e.next() (1, 1) >>> e.next() (2, 2) >>> e.next() (3, 3) >>> e.next() 

Источник

Как работает функция enumerate() в Python?

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

Итак, функция enumerate() в Python принимает некий набор данных в качестве параметра и возвращает объект enumerate.

Этот объект возвращается в формате пар ключ-значение, где ключи — это соответствующие индексы элементов, а значения — сами элементы из переданного набора данных.

Но давайте сперва поговорим о синтаксисе и параметрах функции enumerate().

Синтаксис функции enumerate() в Python

Синтаксис функции enumerate() выглядит следующим образом:

Функция enumerate() принимает два параметра: iterable и start .

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

Как использовать функцию enumerate() в Python

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

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

Пример №1: функция enumerate() с одним параметром

names = ["John", "Jane", "Doe"] enumNames = enumerate(names) print(list(enumNames)) # [(0, 'John'), (1, 'Jane'), (2, 'Doe')]

В приведенном выше примере мы создали список, состоящий из трех имен.

Затем мы преобразовали переменную names в объект enumerate и сохранили результат в переменной с именем enumNames .

Далее мы захотели, чтобы наш объект был выведен в виде списка, поэтому мы сделали следующее: list(enumNames) .

При выводе на консоль результат будет выглядеть так: [(0, ‘John’), (1, ‘Jane’), (2, ‘Doe’)] .

Как видите, результат мы получили в виде пар ключ-значение. Первый индекс — 0, он связан с первым элементом в нашем списке имен names , второй — 1, связан со вторым элементом в списке names и так далее.

Обратим внимание, что в нашем примере мы использовали только первый параметр функции enumerate().

В следующем примере мы используем оба параметра, чтобы вы увидели разницу.

Пример №2: функция enumerate() с указанием начального индекса

names = ["John", "Jane", "Doe"] enumNames = enumerate(names, 10) print(list(enumNames)) # [(10, 'John'), (11, 'Jane'), (12, 'Doe')]

Здесь мы добавили второй параметр в функцию enumerate() , написав enumerate(names, 10) .

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

Результат будет таким: [(10, ‘John’), (11, ‘Jane’), (12, ‘Doe’)] .

Мы видим, что первый индекс равен 10, второй 11 и так далее. Таким образом, с помощью второго аргумента start мы можем установить любой начальный индекс для наших элементов.

Как перебрать результат функции enumerate() в Python

Вот простой пример, показывающий, как мы можем перебирать полученный в результате объект enumerate:

names = ["John", "Jane", "Doe"] enumNames = enumerate(names) for item in enumNames: print(item) # (0, 'John') # (1, 'Jane') # (2, 'Doe')

Используя цикл for , мы прошлись по нашему объекту с помощью следующей команды: for item in enumNames . Подробнее про тонкости использования цикла for можете узнать в статье «Цикл for в Python: тонкости написания».

На выходе мы получили элементы исходного объекта, выведенные в формате пар ключ-значение.

Заключение

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

Наконец, мы увидели, как можно перебирать вывод функции enumerate() с помощью цикла for .

Надеемся, данная статья была вам полезна! Успехов в написании кода!

Источник

Читайте также:  Vector in python example
Оцените статью