0

Few elements in the list contain square brackets and i want to replace brackets for those elements.

I am using Python 3 to solve this problem

List:-

['Europe',
 'Indonesia',
 'Singapore',
 'United Kingdom',
 ['United States of America'],
 'New Zealand',
 'Singapore',
 'Canada',
 ['South America', 'South America', 'South America', 'South America'],
 'Australia']

Expected List:-

['Europe',
 'Indonesia',
 'Singapore',
 'United Kingdom',
 'United States of America',
 'New Zealand',
 'Singapore',
 'Canada',
 'South America', 'South America', 'South America', 'South America',
 'Australia']
Amy
  • 45
  • 5
  • Its not duplicate. In my problem only few elements contain square bracket – Amy Aug 09 '19 at 04:04
  • If you have more than one layer to flatten: https://stackoverflow.com/questions/12472338/flattening-a-list-recursively – FObersteiner Aug 09 '19 at 06:45
  • The answer for your specific case in the duplicate target is [here](https://stackoverflow.com/a/40857703/7851470). – Georgy Aug 09 '19 at 09:11

2 Answers2

1

You essentially have lists within lists, you could try something like this function. It will see if you have a sublist, and if so, it will extract out all of the elements within that sublist and add them to return_list.

def clean_list(list):
    return_list = []
    for i in list:
        if type(i) == list:
            for j in i:
                return_list.append(j)
        else:
            return_list.append(i)
    return return_list
0

As @Chris Turgeon earlier pointed out you have a list within a list. Here is something I have used with similar situations. Essentially I modify the original list with pop and insert and use enumerate when loopin through the original list.

firstList = ['Europe',
 'Indonesia',
 'Singapore',
 'United Kingdom',
 ['United States of America'],
 'New Zealand',
 'Singapore',
 'Canada',
 ['South America', 'South America', 'South America', 'South America'],
 'Australia']

for index, item in enumerate(firstList):
    if isinstance(item, list):
        firstList.pop(index)
        for listTwoItem in item:
            firstList.insert(index, listTwoItem)
            index += 1
eemilk
  • 1,375
  • 13
  • 17