Search code examples
pythonformatlist-comprehensionwhitespace

Adding whitespaces around each element of a list of lists python


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 "]


Solution

  • 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]