Python Object Referencing Workaround

Viewed 32

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

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

List concatenation returns a new list object.

outer_list = ['a', 'b']
inner_list = [1, 2, 3]

print([outer_list + [item] for item in inner_list])

You could also achieve using map

print(list(map(lambda item: outer_list + [item], inner_list )))
Related