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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With