Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
Why do we need the 'index' variable to move down a row in a list of list? Doesn't the 'for loop' do that automatically?

can someone please help me bridge my gap in understanding?

Why is the 'index' variable necessary to 'move down' a row in a list of lists? I thought a for loop did that automatically.

#I am working with the following data

url = "https://en.wikipedia.org/wiki/List_of_helicopter_prison_escapes"

data = data_from_url(url)

for row in data[:3]: #I use this because I have to get rid of the information in the column named 'Details'
    print(row)
#"The assignment says: Initialize an index variable with the value of 0. The purpose of this variable is to help us track which row we're modifying." - (I don't get this explanation)

index = 0
for row in data:
    data[index] = row[:-1]
    index += 1

#Why is the following code not enough if a 'for loop' iterates through each row in a list of lists?

for row in data:
    data= row[:-1]
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Let's try both and see what happens:

>>> data = [[1,2,3],[4,5,6],[7,8,9]]
>>> index = 0
>>> for row in data:
...     data[index] = row[:-1]
...     index += 1
...
>>> data
[[1, 2], [4, 5], [7, 8]]

Looks good; all the rows without their last elements.

>>> data = [[1,2,3],[4,5,6],[7,8,9]]
>>> for row in data:
...     data = row[:-1]
...
>>> data
[7, 8]

Oops, that's just the last row without its last element, since that's what you assigned to data.

There are less convoluted and error-prone methods to accomplish the task without resorting to indexing, though.

For instance,

>>> data = [[1,2,3],[4,5,6],[7,8,9]]
>>> data = [it[:-1] for it in data]
>>> data
[[1, 2], [4, 5], [7, 8]]
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda