1

I have the following lista that contains lists and strings:

['IBERDROLA', 'ACCOR\xa0SA', ['ADMIRAL'], ['ADECCO', 'IAG']]

I would like to make it a flat_list with this output:

['IBERDROLA', 'ACCOR\xa0SA', 'ADMIRAL', 'ADECCO', 'IAG']

Probably I might not be using the correct keywords to find the desired answer, buy I only found Making a flat list out of list of lists in Python (with no str like mines) into a flat_list which gives the following output:

flat_list = [item for sublist in lista for item in sublist] 

['I', 'B', 'E', 'R', 'D', 'R', 'O', 'L', 'A', 'A', 'C', 'C', 'O', 'R', '\xa0', 'S', 'A', 'ADMIRAL', 'ADECCO', 'IAG']
JamesHudson81
  • 2,215
  • 4
  • 23
  • 42

3 Answers3

2

You can use the isinstance() function to check the type of a list item:

lista = ['IBERDROLA', 'ACCOR\xa0SA', ['ADMIRAL'], ['ADECCO', 'IAG']]
flat_list = []

for item in lista:
    if isinstance(item, list):
        flat_list.extend(item)
    else:
        flat_list.append(item)
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
2

Assuming your list is stored as variable l, you can use a ternary operator with a test of isinstance as a condition:

[i for s in l for i in (s if isinstance(s, list) else (s,))]
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Exactly what I wanted to post, but any particular reason why `(s,)` and not `[s]`? – tobias_k Oct 24 '18 at 13:40
  • 1
    Only because tuples have [slightly less overhead](https://stackoverflow.com/questions/68630/are-tuples-more-efficient-than-lists-in-python) than lists, so unless it's meant to be mutated, I prefer using tuples whenever possible. – blhsing Oct 24 '18 at 13:41
  • FWIW, this happens to be noticeably slower than a simple loop, perhaps due to the nested generator expression and building tuple objects for each string. – Eugene Yarmash Oct 24 '18 at 13:58
0
   lst = ['IBERDROLA', 'ACCOR\xa0SA', ['ADMIRAL'], ['ADECCO', 'IAG']]
   new_lst = reduce(lambda x,y:x+y,[val if isinstance(val,list) else [val] for val in lst])
   print new_lst

   Result : ['IBERDROLA', 'ACCOR\xa0SA', 'ADMIRAL', 'ADECCO', 'IAG']
Narendra Lucky
  • 340
  • 2
  • 13