Print indices of list Python
To print the indices of a list in Python, we can use the enumerate() function, which allows us to loop through the list and get both the index and the value of each element. Here's a simple example:
my_list = ['a', 'b', 'c', 'd', 'e']
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")
Explanation:
Here, the enumerate(my_list) function returns an iterable that provides a tuple containing the index and the value of each element in the list. The for loop iterates over these tuples, and the print statement outputs the index and the value.
Output:Index: 0, Value: a
Index: 1, Value: b
Index: 2, Value: c
Index: 3, Value: d
Index: 4, Value: e
Additional Example
If you only want to print the indices and not the values, you can modify the code as follows:
my_list = ['a', 'b', 'c', 'd', 'e']
for index, _ in enumerate(my_list):
print(f"Index: {index}")
Output of the above code:
Index: 0
Index: 1
Index: 2
Index: 3
Index: 4
Related Articles
Trigonometric functions Python Numpy
Python convert dataframe to numpy array
Convert binary to decimal in Python
Multiply all elements in list Python
Multiply each element of a list by a number in Python
Python NumPy: Overview and Examples
Convert Python list to numpy array
numpy dot product
Python Pandas Plotting
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python take screenshot of specific window
Read data from excel file using Python Pandas
Quick Introduction to Python Pandas
Python requests GET method
Python Convert XML to CSV
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Bouncing ball game code in Python
Remove character from string Python
Python raise keyword