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