is there a way to combine lists without copying the content?

Question:

I basically want to combine the references to the two lists in a way that doesn’t copy the content.

for example:

list1 = [1, 2, 3]
list2 = [4, 5, 6]

combined_list = combine(list1, list2)
# combined_list = [1, 2, 3, 4, 5, 6]

list1.append(3)
# combined_list = [1, 2, 3, 3, 4, 5, 6]
Asked By: Harris001

||

Answers:

You can refer to collections.ChainMap to implement a ChainSeq. Here is a print only version:

from itertools import chain


class ChainSeq:
    def __init__(self, *seqs):
        self.seqs = list(seqs) if lists else [[]]

    def __repr__(self):
        return f'[{", ".join(map(repr, chain.from_iterable(self.seqs)))}]'

Test:

>>> list1 = [1, 2, 3]
>>> list2 = [4, 5, 6]
>>> combined_list = ChainSeq(list1, list2)
>>> combined_list
[1, 2, 3, 4, 5, 6]
>>> list1.append(3)
>>> combined_list
[1, 2, 3, 3, 4, 5, 6]
Answered By: Mechanic Pig

simlpicity is important in python
you can use extend method

lst1 = [1, 2, 3]
lst2 = [4, 5, 6]
lst = []
lst.extend(lst1)
lst_extend(lst2)
Answered By: mehdi mosavi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.