본문 바로가기
Study Note/Python

Enumerate()

by jhleeatl 2024. 5. 8.

 

 

 

 

The `enumerate()` function  takes an iterable object (such as a list, tuple, or string) as input and is used to iterate over it while keeping track of the index and the corresponding element.

 

It's commonly used in for loops when you need to access both the index and the element of each iteration.

The syntax of the `enumerate()` function is as follows:

enumerate(iterable, start=0)

 


- `iterable`: The iterable object for which you want to generate indices and elements.
- `start`: An optional parameter specifying the starting index value. By default, it starts from 0. If specified, the indices will start from this value.

The `enumerate()` function generates a tuple for each element, where the first element of the tuple is the index, and the second element is the corresponding element from the iterable object.

 

Here is an example:

my_list = ['apple', 'banana', 'orange']

for index, fruit in enumerate(my_list):
    print(f"Index {index}: {fruit}")


```Result``````
Index 0: apple
Index 1: banana
Index 2: orange
```````````````



Using `enumerate()` allows you to access both the index and the element simultaneously in a loop, making your code more concise and readable.

 

Another example

 

my_string = "Hello, World!"

for index, char in enumerate(my_string):
    print(f"Character at index {index}: {char}")

Result
Character at index 0: H
Character at index 1: e
Character at index 2: l
Character at index 3: l
Character at index 4: o
Character at index 5: ,
Character at index 6:  
Character at index 7: W
Character at index 8: o
Character at index 9: r
Character at index 10: l
Character at index 11: d
Character at index 12: !

 

'Study Note > Python' 카테고리의 다른 글

Seaborn plot (Scatter, Hist, and Box)  (0) 2024.05.16
Library (Pandas, Seaborn, Matplotlib, Numpy) - Iris Data  (0) 2024.05.14
Missing data handling  (0) 2024.05.02
Taitanic data analysis  (0) 2024.04.30
Python Data Types  (0) 2024.04.25