How do I assign the last value of an array to a variable?

Asked

Viewed 444 times

0

I need to put in a variable the last value of a vector, problem is that this vector can vary in size. Is there any direct function that brings the last vector value?

I tried to use a variable to check the vector size, but it didn’t work, below a little code

ultimo = len(tensao)
mod_elasticidade = tensao[ultimo]

2 answers

3

There is the possibility to use positions reversed, array[-1], array[-2], and so on. Example:

array = [1,2,3,4,5]
print(array[-1])
#O retorno será '5'
print(array[-2])
#O retorno será '4'

So:

mod_elasticidade = tensao[-1]

If you want to do it using the function len() also you can, you were getting error, because the function len() returns the number of elements counting from 1:

array = [1,2,3,4,5]
print(len(array))
#O retorno será '5'

Already positions, are counted from 0, and in this example range from 0 to 4:

array = [1,2,3,4,5]
#A posição 0 é o 1, a 1 é o 2, e assim em diante
print(array[0])
#O retorno será '1'
print(array[4])
#O retorno será '5'

So:

ultimo = len(tensao)-1 # -1, para reduzir essa diferença

mod_elasticidade = tensao[ultimo]

0

The function len() returns the amount of elements contained in a list.

In Python, the first element of a list has index 0, while the last element has an index len() - 1.

idx_ultimo = len(tensao) - 1
mod_elasticidade = tensao[ idx_ultimo ]

Computationally speaking, retrieving the last element of a list is a very common operation to be performed, and in Python, everything can become much simpler through slice notation:

mod_elasticidade = tensao[-1]  # Retorna o ultimo elemento da lista.

It is good to remember that the attempt to access the last element of an empty list causes an exception of type IndexError. A possible solution to treat this case without an exception would be something like:

mod_elasticidade = tensao[-1] if tensao else None

Browser other questions tagged

You are not signed in. Login or sign up in order to post.