0

Assume

my_list = [[1], [2], [3], ["a"], [5]]

I want

my_imm = ImmutableList(mylist)

such that

my_imm[2][0] = 0

would either throw an error, or not change my_list[2].

Is there such a construct without copying all the data?

Also assume my_list is long, and I wouldn't want a conversion, but rather an lazy iterator.


Notice this is not a duplicate of this, because I want THE ELEMENTS to be immutable.

Tuples won't solve that out of the box.

Gulzar
  • 23,452
  • 27
  • 113
  • 201

2 Answers2

1

Use a generator to get the elemets as tuples:

my_imm = (tuple(e) for e in my_list)
pbacterio
  • 1,094
  • 6
  • 12
0
from collections.abc import Iterable
from typing import Iterator


class MyImm(Iterable):
    def __init__(self, iterable: Iterable):
        self._iterator = iter(iterable)

    def __next__(self) -> Iterator:
        return tuple(next(self._iterator))

    def __iter__(self):
        return self


my_list = [[1], [2], [3], ["a"], [5]]
my_imm = MyImm(my_list)

for i, e in enumerate(my_imm):
    print(my_list)
    if i == 2:
        e[0] = 0

print(my_list)

output:

"C:/code/EPMD/Kodex/Applications/EPMD-Software/LocationService/ablation/ssss.py",
line 22, in <module>
   e[0] = 0 TypeError: 'tuple' object does not support item assignment [[1], [2], [3], ['a'], [5]] [[1], [2], [3], ['a'], [5]]
[[1], [2], [3], ['a'], [5]]

Gulzar
  • 23,452
  • 27
  • 113
  • 201