Obligatory: don't use list
as a variable or parameter name, since it overwrites the builtin list
type.
The reason the first example doesn't work is that each value from the list is assigned to the variable named element
, but reassigning element
to a different value only modifies that variable; it doesn't mutate the original value in the list.
The second example does what you want because the []
operator allows you to mutate the list.
Note also that there is an example between mutating the original list and returning a new list that's a modified version of the original!
>>> data = [1, 2, 3, 4, 5]
>>> def convert(a):
... """Returns a new list filled with 2s."""
... return [2 for i in a]
...
>>> def mutate(a):
... """Modifies the list to fill it with 2s."""
... for i in range(len(a)):
... a[i] = 2
... return a
...
>>> convert(data)
[2, 2, 2, 2, 2]
>>> data
[1, 2, 3, 4, 5]
>>> mutate(data)
[2, 2, 2, 2, 2]
>>> data
[2, 2, 2, 2, 2]
Both functions return a list that's filled with 2s, but convert
returns a new list (leaving the original data
unchanged unless you assign the new value to it), whereas mutate
modifies the original list as well.
Finally, there is a way to use the []
operator as a shortcut to mutate the entire list at once:
>>> def mutate(a):
... a[:] = [2 for _ in a]
...
>>> data = [1, 2, 3, 4, 5]
>>> mutate(data)
>>> data
[2, 2, 2, 2, 2]