I accidently noticed that directly updating elements in a list of lists was working.
There are lots of Q&A about updating a list of lists. Yet all the answers I inspected indicate that
- inside the iteration python generates a copy of the list's elements
- changing the copied element does not change the list itself
- you need to use a list comprehension, an index into the list or something alike to change the list
But in the following example I can directly update a list.
All answers I found about the subject are fairly old, so is this later on added to python?
# COMPREHENSION ==================================
li = [
["spam1", "eggs1"],
["spam2", "eggs2"]
]
print("\nCOMPREHENSION ---------------")
print("INPUT", li)
li = [["new", l[1]] for l in li]
print("OUTPUT", li)
# INDEX ===========================================
li = [
["spam1", "eggs1"],
["spam2", "eggs2"]
]
print("\nINDEX -----------------")
print("INPUT", li)
for index, l in enumerate(li):
li[index] = ["new", l[1]]
print("OUTPUT", li)
# IN PLACE ========================================
li = [
["spam1", "eggs1"],
["spam2", "eggs2"]
]
print("\nIN PLACE --------------")
print("INPUT", li, " <<<<<<<<<<<<<")
for i in li:
i[0] = f'new'
print("OUTPUT", li, " <<<<<<<<<<<<<")
Result
COMPREHENSION ---------------
INPUT [['spam1', 'eggs1'], ['spam2', 'eggs2']]
OUTPUT [['new', 'eggs1'], ['new', 'eggs2']]
INDEX -----------------
INPUT [['spam1', 'eggs1'], ['spam2', 'eggs2']]
OUTPUT [['new', 'eggs1'], ['new', 'eggs2']]
IN PLACE --------------
INPUT [['spam1', 'eggs1'], ['spam2', 'eggs2']] <<<<<<<<<<<<<
OUTPUT [['new', 'eggs1'], ['new', 'eggs2']] <<<<<<<<<<<<<