Problem editing a list in Python 3

Asked

Viewed 90 times

0

I do not understand what is happening with this excerpt of code. What was expected was that when imprint the list at the end he the elements of her split, but is returning the list as if nothing had happened.
(Each element of the initial list is a phrase. when I give . split() I want him to turn each of these elements into a new list where the words are separated)

x = open ('exemplo1.txt','r')
lista = x.readlines()

for l in lista:
    l = l.split()

print(lista)
  • The list is not changed at any time, for all intents and purposes is as if your for did not exist. For what you want to see is the variable l but print the lista. You can put one print(l) within the for to see the result of str.split()

3 answers

4

Do

for l in lista:
    l = l.split()

Is similar to do:

for i in range (0,len(lista)):
    l = lista[i]
    l = l.split()

Which is equal to:

for i in range (0,len(lista)):
    l = lista[i].split()

Note that only the variable value l has been changed, but not the lista[i]. That’s why lista is not amended.

One solution to this problem, following the suggestion of Bruno’s comment, is to use list by comprehension:

x = open ('exemplo1.txt','r')
lista = x.readlines()

lista = [l.split() for l in lista]

print(lista)
  • 1

    +1. For the answer to be more complete, it could include an example, showing how to obtain the result that Julian wants. For example, using enumerate or list by comprehension [l. split() for l in lista]

1

Good morning. What’s going on in your code is an indentation error.

The Correct would be:

x = open ('exemplo1.txt','r')
lista = x.readlines()

for l in lista:    # Para cada l na lista
    l = l.split()  # l recebera um .split()
    print(l)       # E mostrará cada l 

Thus, for each element within the list, the loop for will print the line.

The l.split() exists only within the loop for, due to Python’s indentation rule.

If you want to add the value with split() the other list, Voce can use a lambada, or you can for example create an empty list above and then add new values to it:

 x = open ('exemplo1.txt','r')
lista = x.readlines()

nova_lista = []
for l in lista:    # Para cada l na lista
    l = l.split()  # l recebera um .split()
    nova_lista.append(l) # Adiciona o valor para a nova lista   
print(nova_lista)   
  • Remembering only, that the .split() no internal assignment, will separate each value within the l us spaces.

  • How to trade lista for l is an indentation error?

  • That’s not what I said, so I put the code there. The l.split() only exists within the loop for. If he needs to create another list with the split elements, he could either lambda it or create the empty list first. And yes, there is the error of indentation, because the print(l) should stay inside the for.

  • But there is no print(l) in his code, that’s what I meant...

  • @Thank you very much. But I still don’t understand why the list isn’t changed when I change a 'l'. I thought that when I made a "l = l.split" that line in the list would be changed and , so when I printed the list it would appear in its new form.

  • In place of nova.append(l), the correct is nova_lista.append(l).

  • This is because with the Voce TAB it changes the indentation layer the code is running. at the line below the for Voce put a tab, and then the l = l.split() This means in practice, that this l with split only exists "within the for

  • We can say, that the l this 'Encapsulated' inside the for.

  • To complement on indentation. Python, like most languages, runs the top-down code, and from left to right. The simplest way to understand the indentation would be to turn the monitor sideways, the l = l.split() would be inside the loop for

Show 4 more comments

0

Opa,

You have to update the list value in the loop for

x = open ('exemplo1.txt','r')
lista = x.readlines() # a lista está parada aqui

for l in lista: # aqui está sendo apenas passado os valores da lista para um variavel.
    l = l.split() # aqui está sendo apenas atualizado o valor na própria variável do laço

print(lista) # printando a lista do mesmo jeito que foi declarada

You have to interact with the for within the loop itself.

x = open('exemplo1.txt','r')
lista = x.readlines()

# aqui pode usar o enumerate pra pegar o index da lista e valor
for i, l in enumerate(lista):
   # ao mesmo tempo que dividi a lista com split, você altera o valor na mesma posição.
   lista[i] = lista[i].split()

print(lista)

The output in this case will be a list of all values of the list that was traversed by the loop.

[ ['exemplo', exemplo2'], ['exemplo3', 'exemplo4'], ... ]

Browser other questions tagged

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