-1

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.

Cleb
  • 25,102
  • 20
  • 116
  • 151
lkkkk
  • 1,999
  • 4
  • 23
  • 29

3 Answers3

7

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.

msvalkon
  • 11,887
  • 2
  • 42
  • 38
1

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

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

Don't worry! Try them!

a[len(a)-1]

or

a[-1]

Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43