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

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 value of the vector?

I tried to use a variable to check the size of the vector, but it did not work, below some of the code

ultimo = len(tensao)
mod_elasticidade = tensao[ultimo]
    
asked by anonymous 28.06.2018 / 13:17

2 answers

3

It is possible to use the positions of inverted form, 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'

Then:

mod_elasticidade = tensao[-1]

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

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

The positions are counted from 0, and in this example they 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'

Then:

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

mod_elasticidade = tensao[ultimo]
    
28.06.2018 / 13:32
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 index len() - 1 .

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

Computationalally speaking, retrieving the last element from a list is a very common operation to execute, and in Python , everything can be much simpler with slice notation :

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

It's worth remembering that attempting to access the last element of an empty list causes an exception of type IndexError . A possible solution to handle this case without an exception would be something like:

mod_elasticidade = tensao[-1] if tensao else None
    
28.06.2018 / 20:18