Python list method index question, find the last element in the list.

Asked 2 years ago, Updated 2 years ago, 151 views

The language is Python.

I have a question about using index method, which is one of Python's methods.

For example, When a_list=[1,2,3,1,4], If you use the index method, you will first put 0 which is the index of the closest 1, but how do you output the index of the last element?

Should I use the reverse method and the index method?

Thank you for your answer Have a great day!

python method index

2022-09-20 10:20

1 Answers

https://docs.python.org/3.12/tutorial/introduction.html#lists

# a = index
# b = Index (in reverse order)
list_a = [1, 2, 3, 4, 5]
# # a       0  1  2  3  4
# # b      -5 -4 -3 -2 -1

print(list_a[4], list_a[-1])
>> 5, 5


2022-09-20 10:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.