-2

I want to convert this list

myList = [[a], [b], [c]]

Into this list

cleaned_list = [a, b, c]

Is there any solution?

2 Answers2

1
my_list = [['a'], ['b'], ['c', 'd']]
cleaned_list = []
for x in my_list:
    for y in x:
        cleaned_list.append(y)
print(cleaned_list)

Also there is another solution:

my_list = [['a'], ['b'], ['c', 'd']]
cleaned_list = [y for x in my_list for y in x]

These solutions also work for sublists with many elements.

Ratery
  • 2,863
  • 1
  • 5
  • 26
-1

Maybe a simple list comprehension:

cleaned_list =  [i[0] for i in myList]
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
  • 2
    Note that this only works for single element sublists – BTables Nov 29 '21 at 15:25
  • The answer was provided according with the OP. – Pedro Maia Nov 29 '21 at 16:20
  • The OP gives no definition for any of the variables. `a = 1,2,3` would be completely valid and not work for the above answer. – BTables Nov 29 '21 at 16:31
  • Of course it would, on OP it states that the result should be `cleaned_list = [a, b, c]` each variable should not be flatted, so if `b = 10` and `c = 20` result would be: `[(1, 2, 3), 10, 20]` – Pedro Maia Nov 29 '21 at 16:36
  • *"Of course it would"*. You should really try to run that code first. With `a = 1,2,3`, `b = 10` and `c=20` you get an error since you'll be trying to subscript an int. Even if `b` and `c` are defined as tuples the output will be `[1,10,20]` since you'll only ever take the first element for each iteration. – BTables Nov 29 '21 at 16:41
  • Have you read the OP ? he's trying to convert `[[a], [b], [c]]` into `[a, b, c]` – Pedro Maia Nov 29 '21 at 16:43
  • I did read the OP and nowhere do I see them say they are single element sublists. Without a full working example you need to take the code as a rough guideline and not make large assumptions. This is evident by the fact that it now appears OP did indeed want support for multi element sublists. – BTables Nov 29 '21 at 17:20