-2

I have the following list:

my_list=[[['A','B'],'C'],[['S','A'],'Q']]

How I can remove the bracket from the first two elements?

output:

my_list=[['A','B','C'],['S','A','Q']]

5 Answers5

1

Slice it in?

for a in my_list:
    a[:1] = a[0]
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
0

This produces the desired output:

[x[0]+[x[1]] for x in my_list]
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0
my_list=[
    [['A','B'],'C'],
    [['S','A'],'Q'],
]

result = [[item1, item2, item3] for (item1, item2), item3 in my_list]
>>> result
[['A', 'B', 'C'], ['S', 'A', 'Q']]
Jason Yang
  • 11,284
  • 2
  • 9
  • 23
0

You can use the flattening solution in Cristian's answer on Flatten an irregular list of lists.

>>> [list(flatten(x)) for x in my_list]
[['A', 'B', 'C'], ['S', 'A', 'Q']]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

Other people have already given the oneline solutions, but let's take a step back and think about how to approach this problem, so you can solve it for yourself.

The tools you need:

for [element] in list: Iterate over each element in a list

list[i]: Get the ith element of a list

list.append(element): Add an element to a list

Let's start with the simple case. We have [['A','B'],'C'] and want ['A','B','C'].

We want to

  • Get the sublist ['A', 'B']
  • Get the single item that isn't in the sublist, 'C'
  • Add the single item into the sublist
  • Make the sublist the main list

Sometimes it's easiest to sketch these things out in the python shell:

>>> l = [['A','B'],'C']
>>> l[0]
['A', 'B']
>>> l[1]
'C'
>>> l[0].append(l[1])
>>> l = l[0]
>>> l
['A', 'B', 'C']

Now, we can build up a function to do this

def fix_single_element(element):
    """
    Given a list in the format [['A','B'],'C']
    returns a list in the format ['A','B','C']
    """
    # We use copy since we don't want to mess up the old list
    internal_list = element[0].copy() 
    last_value = element[1]
    internal_list.append(last_value)
    return internal_list

Now we can use that:

>>> for sublist in my_list:
...     print(sublist)
... 
[['A', 'B'], 'C']
[['S', 'A'], 'Q']

Note that the sublists are exactly the problem we just solved.

>>> new_list = []
>>> for sublist in my_list:
...     new_list.append(fix_single_element(sublist))
... 
>>> new_list
[['A', 'B', 'C'], ['S', 'A', 'Q']]

There are LOTS of ways to do any particular task, and this is probably not the "best" way, but it's a way that will work. Focus on writing code you understand and can change, not the shortest code, especially when you start.

Kaia
  • 862
  • 5
  • 21