본문 바로가기
개념/혼자 공부하는 파이썬

python) Exploring Python's Enumerate Function with Lists

by kiseno 2024. 11. 13.
728x90
반응형
SMALL

 

example_list = [1,2,3,4,5,6,7,8,9]
print("simple print")
print(example_list)
print()

print("enumerate")
print(enumerate(example_list))
print()

print("#list function pull out")
print(list(enumerate(example_list)))
print()

print("loop syntax for combination")
for i, value in enumerate(example_list):
    print("{} 요소는 {}입니다.".format(i, value))


### Source Code Explanation for Each Line
1. `example_list = [1,2,3,4,5,6,7,8,9]`: Initializes `example_list` with numbers from 1 to 9.

2. `print("simple print")`: Prints a string to indicate the start of a simple print operation.

3. `print(example_list)`: Directly prints the contents of `example_list`.

4. `print()`: Prints an empty line for better readability.

5. `print("enumerate")`: Prints a string to indicate the start of demonstrating the `enumerate` function.

6. `print(enumerate(example_list))`: Attempts to print the `enumerate` object created from `example_list`. However, this won't display the list itself but will show an enumerate object memory location.

7. `print()`: Prints an empty line for clarity.

8. `print("#list function pull out")`: Prints a comment indicating the next operation is to convert the `enumerate` object to a list.

9. `print(list(enumerate(example_list)))`: Converts the `enumerate` object of `example_list` into a list and prints it. This showcases how `enumerate` pairs each element with its index in a tuple format.

10. `print()`: Adds an empty line for readability.

11. `print("loop syntax for combination")`: Prints a comment indicating the demonstration of using `enumerate` in a loop.

12. **Loop Explanation**:
    - `for i, value in enumerate(example_list):`: Iterates over `example_list`, with `enumerate` providing each element's index (`i`) and value (`value`).
    - `print("{} 요소는 {}입니다.".format(i, value))`: For each iteration, prints the index and value of the current element in a formatted string. The message is in Korean, translating to "Element {} is {}." 

728x90
반응형
LIST