Search code examples
python-3.xlistappendnested-lists

How to make a nested list in python


Suppose I have a 2 lists in my python script:

my_list = ['hat', 'bat']
other_list = ['A', 'B', 'C']

I want to iterate through other_list and create a nested list for 'bat's that adds '_' + other_list item to a the 'bat' and puts it in a nested list:

 for item in other_list:
    for thing in my_list:
        if thing == 'bat':
            print(thing + '_' + item)

My desired outcome would be new_list = ['hat',['bat_A', 'bat_B', 'bat_C']] How would I achieve this? I tried the below, but it produces this: ['hat', 'hat', 'hat', ['bat_A', 'bat_B', 'bat_C']]

new_list = []
extra = []
for item in other_list:
    for thing in my_list:
        if thing == 'bat':     
            extra.append(thing + '_' + item)
        else:
            new_list.append(thing)
new_list.append(extra)

Solution

  • Try this:

    >>> my_list = ['hat', 'bat']
    >>> other_list = ['A', 'B', 'C']
    >>> new_list=[my_list[0], [f'{my_list[1]}_{e}' for e in other_list]]
    >>> new_list
    ['hat', ['bat_A', 'bat_B', 'bat_C']]
    

    If your question (which is a little unclear) is just about reacting to 'bat' with a different reaction, you can do this:

    my_list = ['hat', 'bat','cat']
    other_list = ['A', 'B', 'C']
    
    new_list=[]
    for e in my_list:
        if e=='bat':
            new_list.append([f'{e}_{x}' for x in other_list])
        else:
            new_list.append(e)
    
    >>> new_list
    ['hat', ['bat_A', 'bat_B', 'bat_C'], 'cat']
    

    Which can be reduced to:

    >>> [[f'{e}_{x}' for x in other_list] if e=='bat' else e for e in my_list]
    ['hat', ['bat_A', 'bat_B', 'bat_C'], 'cat']