Accessing indexes in Python for statements

Asked 1 years ago, Updated 1 years ago, 71 views

items = [8, 23, 45, 12, 78] without using index variables as shown below Is there a way to print the index?

index = 0
for item in items:
    print(index, item)
    index += 1

loops python

2022-09-22 22:36

1 Answers

Writing additional state variables, such as index variables, is not Python.

Use the built-in function enumerate() (both Python versions are available)

items = [8, 23, 45, 12, 78]
for idx, val in enumerate(items):
    print idx, val


2022-09-22 22:36

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.