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:

Python: Access the index of a list

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:

Flowchart: Access the index of a list

Python Code Editor:

Previous: Write a Python program to get the difference between the two lists.
Next: Write a Python program to convert a list of characters into a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/list/python-data-type-list-exercise-20.php