Suppose I have the list as
a = [0.0021, 0.12, 0.1224, 0.22]
I have to extract the last number from the above list, so my answer should be 0.22
without using a[3]
, because the number of the elements in the list always keep changing.
Suppose I have the list as
a = [0.0021, 0.12, 0.1224, 0.22]
I have to extract the last number from the above list, so my answer should be 0.22
without using a[3]
, because the number of the elements in the list always keep changing.
You're talking about a list. Arrays in python are usually numpy.arrays. They are a completely different data structure.
You can achieve what you want like this:
>>> array = [0.0021, 0.12, 0.1224, 0.22]
>>> array[-1]
0.22
>>>
Negative indexing starts at the end of the list, thus array[-1]
will always be the last element in the list, array[-2]
the second last and so forth.
The appropriate name of [...]
is a list. As you know, you can access to an element of a list using an index, like
some_list = [1, 2, 3]
print some_list[0] # first element
But you can also use negative indices:
print some_list[-1] # last element: 3
print some_list[-2] # one before the last element: 2
Note that this will "count" elements from right to left