Adding whitespaces around each element of a list of lists python

Question:

I want to add whitespaces around each element within a list of lists

data = [["hello", "world"], ["python", "is", "cool"]]
-->
data = [[" hello ", " world "], [" python ", " is ", " cool "]]
data_new = ["hello world", "python is cool"]
data_new2 = [x.split(" ") for x in data_new]
--> [["hello", "world"], ["python", "is", "cool"]]
data_new2 = [' {0} '.format(word) for elem in data_new2 for word in elem]
print(data_new2[:10])
--> [" hello ", " world ", " python ", " is ", " cool "]

Asked By: Fraser

||

Answers:

You don’t need to split, use a nested list comprehension (here with a f-string):

data = [["hello", "world"], ["python", "is", "cool"]]

data2 = [[f' {x} ' for x in l] for l in data]

Output:

[[' hello ', ' world '], [' python ', ' is ', ' cool ']]

Alternative input:

data = ["hello world", "python is cool"]

data2 = [[f' {x} ' for x in s.split()] for s in data]
Answered By: mozway

While list comprehension is cool and powerful, there are cases where using it simply saves lines while only making code harder to read. Therefore, I suggest abandoning list comprehension in favor of a nested for loop. Yes, it’s more lines, but it is easier to debug and you’ll know what it does when you look at it in two years:

data = [["hello", "world"], ["python", "is", "cool"]]
for i, sublist in enumerate(data):
    for j, word in enumerate(sublist):
        data[i][j] = " " + data[i][j] + " "

To clarify, list comprehension definitely has it’s place – I just don’t think it’s here.

Answered By: jhschwartz