Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Object Referencing Workaround

Consider the code below:

    outer_list = ['a', 'b', 0]
    inner_list = [1, 2, 3]
    
    final = []
    for item in inner_list:
        outer_list[-1] = item
        final.append(outer_list)
    
    print(final)

with output : [['a', 'b', 3], ['a', 'b', 3], ['a', 'b', 3]]

My intended output is: [['a', 'b', 1], ['a', 'b', 2], ['a', 'b', 3]]

I understand this has to do with the fact that Python uses object referencing but i cant seem to find a way around this.

Anyone with a solution or alternative i'd appreciate

like image 828
Mthulisi Avatar asked Feb 15 '26 22:02

Mthulisi


1 Answers

Yes you're right. Your assignment at line 6 modifies list outer_list and your append call add references to that list in final. You can work on a copy of outer_list to get your result :

    outer_list = ['a', 'b', 0]
    inner_list = [1, 2, 3]
    
    final = []
    for item in inner_list:
        l = outer_list.copy()
        l[-1] = item
        final.append(l)         
    
    print(final)
like image 58
qouify Avatar answered Feb 17 '26 15:02

qouify



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!