#! /usr/bin/python3 # =================================================================== # test passing a list into a class and making a copy of it # so that it is independent from the external list # =================================================================== from copy import deepcopy # ------------------------------------------------------------------- # ---- class definition # ------------------------------------------------------------------- class testClass: def __init__(self,lst): self._lst = lst.deepcopy() def dump_list(self): i = 0; print() print('---class list (copy of external list)----------') i = 0 for l in self._lst: print(f'[{i}] {l}') i+= 1 print('-----------------------------------------------') def set_list_value(self,idx,value): self._lst[idx] = value def remove_list_value(self,value): self._lst.remove(value) def remove_list_index(self,idx): self._lst.remove(self._lst[idx]) # ------------------------------------------------------------------- # ---- support function: dump list # ------------------------------------------------------------------- def dump_list(lst): print('---external list-------------------------------') i = 0 for l in lst: print(f'[{i}] {l}') i += 1 print('-----------------------------------------------') # ------------------------------------------------------------------- # ---- main # ------------------------------------------------------------------- if __name__ == '__main__': lst = [ 1, 2, 3, 'abc', 'xyz' ] test = testClass(lst) print() dump_list(lst) test.dump_list() print() print('==== inset and remove values from class list ====') print() print('replacing idx=[2] value="qrs"') test.set_list_value(2,'qrs') print('replacing idx=[3] value=45') test.set_list_value(3,45) print() print('removing index = 4') test.remove_list_index(4) print('removing value 1') test.remove_list_value(1) print() dump_list(lst) test.dump_list()