Python 3 Negative Indices

Asked

Viewed 500 times

6

So, guys. I’m new to python and I wanted to know the following:

Is there any way to know the negative input of an item in a list?

For example, I have the following code:

lista = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
lista.index('a')
0
lista.index('g')
6

I would like to know if there is any method that returns the Dice backwards, this way:

lista.index('g')
-1
lista.index('a')
-7

I couldn’t find anything like this.

  • 7

    lista.index('a') - len(lista)?

  • Thanks!! It worked :D

  • ... or use the reverse list -lista[::-1].index('a')-1 (ignore: I’m playing charades!)

3 answers

1

According to @bfavaretto’s comment, the answer is:

lista.index('a') - len(lista)
  • 2

    You just need to check if there really is a 'a'

  • 1

    As comment is good, in response it would be convenient to elaborate a little more.

0

def returnOpposite(li): for i in range(len(li) - 1, -1, -1): print(f'Your element is: {li[i]}, Your opposite index: {i * -1 -1}')

returnOpposite(['a', 'b', 'c', ’d', 'e', 'f', 'g'])

this solves the problem, the function is basically going through the list backwards and printing the index by multiplying by -1, to leave the way you proposed

-1

Indexes range from 0 to the amount of elements added.

example:

listaN1 = [1,2,3]
""" três pontos (...) é uma Ellipsi , omissão de valor. """
#ou
listaN2 = 'abc' #String em python tbm pode ser lista.

índice = valor           índice = valor 
  0    =  1                 0   =  a
  1    =  2                 1   =  b
  2    =  3                 2   =  c

Accessing using negative index returned the list backwards.

    índice = valor           índice = valor 
     -1    =  3                 -1  =  c
     -2    =  2                 -2  =  b
     -3    =  1                 -3  =  a

#Zero at zero was nowhere, negative zero is the index of the first element.

Example Manipulating the list:

listaN1[**iniciar** : *parar* : **pular**]

listaN1[0:2)]
retorno = dois primeiros elementos, 
listaN1[0:3)]
retorno = três elementos
# OU
listaN1[:2] #OMITIR O PRIMEIRO VALOR, CONSIDERA ZERO

listaN1[2:3] # ultimo elemento.
#pulando  posições, como não digitei muitos numero vera nenhuma diferença.
listaN1[1::3]

#INVERTENDO VALORES, MENOR PARA O MAIOR.
listaN1[::-1]

Browser other questions tagged

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