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
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.
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]
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.