Take the content of a list and append it to another list

后端 未结 7 1698
死守一世寂寞
死守一世寂寞 2020-12-07 08:55

I am trying to understand if it makes sense to take the content of a list and append it to another list.

I have the first list created through a loop function, that

相关标签:
7条回答
  • 2020-12-07 09:28

    To recap on the previous answers. If you have a list with [0,1,2] and another one with [3,4,5] and you want to merge them, so it becomes [0,1,2,3,4,5], you can either use chaining or extending and should know the differences to use it wisely for your needs.

    Extending a list

    Using the list classes extend method, you can do a copy of the elements from one list onto another. However this will cause extra memory usage, which should be fine in most cases, but might cause problems if you want to be memory efficient.

    a = [0,1,2]
    b = [3,4,5]
    a.extend(b)
    >>[0,1,2,3,4,5]
    

    Chaining a list

    Contrary you can use itertools.chain to wire many lists, which will return a so called iterator that can be used to iterate over the lists. This is more memory efficient as it is not copying elements over but just pointing to the next list.

    import itertools
    a = [0,1,2]
    b = [3,4,5]
    c = itertools.chain(a, b)
    

    Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

    0 讨论(0)
提交回复
热议问题