-1

Let's say I have a list:

lista = ['dog', 'cat', 'red blue']

And I want to split the 'red blue' to 'red', 'blue':

lista = ['dog', 'cat', 'red', 'blue']

How could I go about doing that? I've tried:

for x in lista:
    lista.split()

But this doesn't seem to change anything

Robert
  • 33
  • 5
  • 1
    have you really tried that? that code cant even run, cant split a list. – Paritosh Singh Dec 27 '18 at 19:44
  • Read the documentation: `split` returns a list of the items split; it does *not* alter the original object. – Prune Dec 27 '18 at 19:51
  • Another exact same [here](https://stackoverflow.com/questions/13808592/splitting-each-string-in-a-list-at-spaces-in-python) – Sheldore Dec 27 '18 at 19:52
  • A third exact same [here](https://stackoverflow.com/questions/45465661/how-can-i-replace-a-text-delimited-string-list-item-with-multiple-list-items-in) – Sheldore Dec 27 '18 at 19:52

3 Answers3

2

The code

for x in lista:
    lista.split() # lista should be x?

would not change anything because you didn't save the result of split. This will help:

new_list = []
for x in lista:
    new_list += x.split()
lista = new_list # overwrite lista

However, there is also a one-liner to do the same:

lista = [y for x in lista for y in x.split()]
adrtam
  • 6,991
  • 2
  • 12
  • 27
2

Rather than explicitly looping through with a for loop, I'd do something like this:

lista = ['dog', 'cat', 'red blue']
items = ' '.join(lista)  # combines lista into a string separated by spaces
lista = items.split(' ')  # splits the string by space into a list

You can do it in one line:

lista = ' '.join(lista).split(' ')
Dylan
  • 21
  • 3
0

Try this

lista = ['dog', 'cat', 'red blue']

y = []
for x in lista:
    y += x.split()

print(y)  # ['dog', 'cat', 'red', 'blue']
ozcanyarimdunya
  • 2,324
  • 1
  • 18
  • 21