﻿ Python: Access the index of a list - w3resource

# Python: Access the index of a list

## Python List: Exercise - 20 with Solution

Write a Python program to access the index of a list.

Visual Presentation:

Sample Solution:

Python Code:

``````# Define a list 'nums' containing a sequence of numbers
nums = [5, 15, 35, 8, 98]
# Use a 'for' loop with 'enumerate' to iterate through 'nums' and obtain both the index and value of each element
for num_index, num_val in enumerate(nums):
# Print the index and value of each element in 'nums'
print(num_index, num_val)
```
```

Sample Output:

```0 5
1 15
2 35
3 8
4 98
```

Explanation:

In the above exercise -

nums = [5, 15, 35, 8, 98] - initializes a list of numbers with 5 elements.

for num_index, num_val in enumerate(nums): - This is a for loop that iterates over each element of nums and returns both the index of the element and the value of the element using the enumerate function.

print(num_index, num_val) – This line prints out the index and value of each element in nums using the print() function.

Flowchart:

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿