Could someone please offer a concise explanation for the difference between these two Python operations in terms of modifying the list?
demo = [\"a\", \"b\",
In the first example, the variable d
can be thought of a copy of the elements inside the list. When doing d = ""
, you're essentially modifying a copy of whatever's inside the list, which naturally won't change the list.
In the second example, by doing range(len(demo))
and indexing the elements inside the list, you're able to directly access and change the elements inside the list. Therefore, doing demo[c]
would modify the list.
If you do want to directly modify a Python list from inside a loop, you could either make a copy out the list and operate on that, or, preferably, use a list comprehension.
So:
>>> demo = ["a", "b", "c"]
>>> test = ["" for item in demo]
>>> print test
["", "", ""]
>>> demo2 = [1, 5, 2, 4]
>>> test = [item for item in demo if item > 3]
>>> print test
[5, 4]