Search code examples
pythonlistjoinnestedlist-comprehension

Is it possible to use .join() to concatenate a list of strings in a nested list in Python?


I'm trying to use join() in a nested list with an if statement. If the condition is met, I want to combine all indices from [1:-3]. Every time the join() function doesn't join the index.

Input

a = [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd', 'e','f','g'], ['a', 'b', 'c', 'd']]

Expected Output

[['a', 'b', 'c', 'd'], ['a', 'b c d', 'e','f','g'], ['a', 'b', 'c', 'd']]

What I have tried:

a = [' '.join(str(inner_list)) for inner_list in a for i in inner_list if len(inner_list) >= 6 ]

I know the for loop is correct because the following code produces true for a[1][0] and iterates through a[][]. To my understanding, the loop is iterating over the correct part but won't join() from the index [1][1] to [1][3]. This is where I'm very confused.

the index

a = [print("true") for inner_list in a for i in inner_list if len(inner_list) >= 6 ]

Solution

  • You need to slice the inner lists in the loop, but also pass the remaining inner lists as they are if they're smaller than 6 items. Here's an example:

    lst = [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd', 'e', 'f', 'g'], ['a', 'b', 'c', 'd']]
    
    new_lst = [[l[0:1] + [' '.join(l[1:-3])] + l[-3:]] if len(l) >= 6 else l for l in lst]
    print(new_lst)
    
    # Output
    # [['a', 'b', 'c', 'd'], [['a', 'b c d', 'e', 'f', 'g']], ['a', 'b', 'c', 'd']]
    

    join() takes a list as an argument instead of a string, and also try to refrain from using built in types like list as variable names.