0

I am trying to split strings within nested lists, but for whatever reason, the strings do not split as I expect them to. For example, here is a nested list where I have strings that I want to split.

myList=[['letters', ['a b c d e', 'f g h i j']], ['digits', ['0 1 2 3 4', '5 6 7 8 9']]]

I have tried using for loops to split each string, but it doesn't seem to work. I tried using the following code:

for i in myList:
    for j in i[1]:
        j=j.split()

However, it seems to do nothing to the list. I expect that after running the code, myList should contain

[['letters', [['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h', 'i', 'j']]], ['digits', [['0', '1', '2', '3', '4'], ['5', '6', '7', '8', '9']]]]

If I look at each item using print() and repr(), I see the strings that I expect.

for i in myList2:
    for j in i[1]:
        print(repr(j))

prints out

'a b c d e'
'f g h i j'
'0 1 2 3 4'
'5 6 7 8 9'

as I expect, so I am unsure why the split values cannot be written.

2 Answers2

2

The syntax j = j.split() doesn't modify the object referenced by j, it just reference j to a NEW thing : the splitted list, and that have no impact on the main list, you need to create a new one

myList = [[i[0], [j.split() for j in i[1]]] for i in myList]

Heavier, but maybe more understandable syntax

result = []
for i in myList:
    tmp_list = []
    for j in i[1]:
        tmp_list.append(j.split())
    result.append([i[0], tmp_list])
print(result)
azro
  • 53,056
  • 7
  • 34
  • 70
0

You should specify the location in the nested list to overwrite. Modifying your code as follows:

for idx, i in enumerate(myList):
    for ix, j in enumerate(i[1]):
        # j = j.split()
        myList[idx][1][ix] = j.split()

print(myList)

results in required output.

TDeg
  • 66
  • 4