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

Time:08-21

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]

CodePudding user response:

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]
  • Related