Search code examples
pythonlistnested-loops

passing items from list to an empty object in another list


I want to pass items from lists to the empty object in store i.e. I want:

store = [ [['a', 'b'], ['c', 'd']], [] ]

I am getting an unintended result:

lists = [['a', 'b'], ['c', 'd']]

store = [[], []]


counter = 0
for l in lists:
    for s in store:
        s.append(l)

which gives me:

store = [[['a', 'b'], ['c', 'd']], [['a', 'b'], ['c', 'd']]]

Solution

  • If

    store = [ [['a', 'b'], ['c', 'd']], [] ]
    

    is indeed what you want, then you've overshot the mark. The inner loop is unnecessary and will execute your code for each item in store. You have two empty lists in store, thus creating two populated lists in store after the code has run. To just do the first one, you want

    for l in lists:
        store[0].append(l)
    

    Reading your question though I'm not 100% positive that's what you're actually after, esp. given your otherwise mysterious inner loop.

    I read "I want to pass items from lists to the empty object in store" as possibly meaning you're trying to take items from two lists in lists and make them one list in store. If that's what you want, something like this would do the trick:

    for l in lists:
        for i in l:
            store[0].append(i)
    

    which gives you:

    [['a', 'b', 'c', 'd'], []]