Python List Invert Values

Asked

Viewed 177 times

3

I am trying to invert two values within a nested list. Example: In the list list there are two values [[1,11],[2,22],[3,33],[4,44]] and would like to reverse the values for [[11,1],[22,2],[33,3],[44,4]].

The mistake I get:

IndexError: list assignment index out of range
def inverte_valores():

    lista = [[1,11],[2,22],[3,33],[4,44]]
    maior_numero = len(lista)
    reordenar_lista = [[] * 2] * maior_numero
    primeira_posicao = 0
    for primeira_posicao in range(maior_numero):
        reordenar_lista[primeira_posicao][0] = lista[primeira_posicao][1]
        reordenar_lista[primeira_posicao][1] = lista[primeira_posicao][0]
    print(reordenar_lista)

    return reordenar_lista


inverte_valores()
  • This way the two positions will be the same values. Use an auxiliary variable to make the exchange.

1 answer

4


You do not need to swap entries this way. What if the list has more than 2 entries?

In this case, just use reversed to invert the lists:

lista = [[1,11],[2,22],[3,33],[4,44]]

inversos = []
for e in lista:
    inversos.append(list(reversed(e)))

print(inversos) # [[11, 1], [22, 2], [33, 3], [44, 4]]

If you want, you can change the loop by a comprehensilist on, much more succinct and pythonic:

inversos = [ list(reversed(e)) for e in lista ]

Or else:

inversos = [ e[::-1] for e in lista ]

[::-1] uses the syntax of slicing to invert the list.


But if you really want to use the indexes, do so (and it will only work if all the sub-lists have exactly 2 elements):

inversos = []
for e in lista:
    inversos.append([e[1], e[0]])
  • 1

    Thank you hkotsubo!!! Its two versions pythônica worked perfectly.I was wondering why my version was wrong, but there was no way. So I decided to post the doubt here. Thank you

Browser other questions tagged

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