Вам не нужна функция, просто присвойте новый список желаемой позиции, и он заменит предыдущее значение.
l2 = ['Node_50',
['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_20']],
['Node_22', ['Node_44'], ['Node_7', 'Node_40']]
]
lnew = ['Node_1', 'Node_40', 'Node_17']
до
l2[1][3]
возвращает
['Node_20']
затем замените его
l2[1][3] = lnew
после
l2[1][3]
возвращает
['Node_1', 'Node_40', 'Node_17']
Это также можно сделать с помощью функции
def myFUN(LIST, newLIST, indexes):
i,j = indexes
if i >= len(LIST):
print("list index (" + str(i) + ") out of range")
return
elif j >= len(LIST[i]):
print("list index (" + str(j) + ") out of range")
return
else:
LIST[i][j] = newLIST
return LIST
сейчас
myFUN(l2, lnew, indexes)
возвращает
['Node_50', ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_1', 'Node_40', 'Node_17']], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]
, но
myFUN(l2, lnew, (4,1))
возвращает
list index (4) out of range
и
myFUN(l2, lnew, (1,25))
возвращает
list index (25) out of range
Сохранить исходный список без изменений
Для python3
def myFUN(LIST, newLIST, indexes):
res = LIST.copy()
i,j = indexes
if i >= len(LIST):
print("list index (" + str(i) + ") out of range")
return
elif j >= len(LIST[i]):
print("list index (" + str(j) + ") out of range")
return
else:
res[i][j] = newLIST
return res
inPython 2 использовать res = LIST[:]
или res=list(LIST)
.Теперь
myFUN(l2, lnew, indexes)
возвращает
['Node_50', ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_1', 'Node_40', 'Node_17']], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]
, но l2 остается неизменным
l2
возвращает
['Node_50', ['Node_48', 'Node_23', ['Node_12', 'Node_3'], ['Node_20']], ['Node_22', ['Node_44'], ['Node_7', 'Node_40']]]