Search code examples
pythonlistappendextend

Combine lists to get list of lists in python


aa = ['a']
bb = ['b']
aa.extend(bb)
['a', 'b']

In the example above, I would like to combine 2 lists to get list of lists, [['a'], ['b']], but extend does not allow that. How can I achieve it in python?


Solution

  • You get a list of lists, you could go about this way:

    >> aa = ['a']
    >> bb = ['b']
    >> cc = []
    >> cc.append(aa)
    >> cc
    [['a']]
    >> cc.append(bb)
    >> cc
    [['a'], ['b']]   
    

    Or another way could be:

    >> dd = list((aa,bb))
    >> dd
    [['a'], ['b']] 
    

    I suggest using the append keyword as it makes it easier to use it within a loop.