Search code examples
pythonlistsquare-bracket

How to flatten extra dimensions in lists down into a single dimension for Python?


Question1. Do you always have to convert a list to string to remove square brackets?

Main Question. I want to remove extra square brackets of a list nested in a list. The [] index of the nested list will change when the words change

Example

Words = ['Red Shirt', ['Minions', 'Expendables', 'Cannon Fodder']]


Solution

  • It looks like you're looking to flatten a list -- or the process of removing the "extra dimensions" of a list of lists down into a single dimension.

    There's a lengthy discussion on in the thread linked here, but I have linked to my preferred solution https://stackoverflow.com/a/952952/9453914

    Your solution will be a little different as you'll first need to add a few more brackets to make your life a little easier, however, this should work for the example given above

    Words = ['Red Shirt', ['Minions', 'Expendables', 'Cannon Fodder']]
    words = [[entry] if type(entry) == str else entry for entry in Words ]
    flattened = [word for l in words for word in l]
    flattened
    >>> ['Red Shirt', 'Minions', 'Expendables', 'Cannon Fodder']
    

    Where we need to nest 'Red Shirt' in its own list first so flattening the entry doesn't start splitting the string into individual characters.